Part Number Hot Search : 
004A11L T89C51 TL494I FBR3030 MA4100 LBN12014 P50N06 SMB43CA
Product Description
Full Text Search
 

To Download ATA6614Q-14 Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  9240h-auto-10/14 general features single-package fully-integrated avr ? 8-bit microcontroller with lin transceiver, 5v regulator (85ma current capability) and watchdog very low current consumption in sleep mode 32kbytes flash memory for application program supply voltage up to 40v operating voltage: 5v to 27v temperature range: t case ?40c to +125c qfn48, 7mm 7mm package ata6614q 32k flash microcontroller with lin transceiver, 5v regulator and watchdog datasheet
ata6614q [datasheet] 9240h?auto?10/14 2 1. description atmel ? ata6614q is a system-in-package (sip) product, which is particularly suited for complete lin-bus slave-node applications. it consists of two ics in one package supporting hi ghly integrated solutions for in-vehicle lin networks. the fir st chip is the lin-system-basis-chip (lin- sbc) atmel ata6630, which has an integr ated lin transceiver, a 5v regulator (85ma) and a window watchdog. the second chip is an au tomotive microcontroller from atmel?s series of avr ? 8-bit microcontroller with advanced risc architecture and 32kby tes of flash (atmel atmega328p). all pins of the avr microcontroller and almost all pins of t he lin system basis chip are bonded out to provide customers the same flexibility for their applications as they have when using discrete parts. the atmel ata6614q is pin compatible to the atmel ata6612p/ata6613p. in section 2. ?pin configuration? on page 3 you will find the pin configuration for the complete sip. in section 3. ?absolute maximum ratings? on page 5 to section 5. ?microcontroller block? on page 30 the lin sbc is described, and in section 7. ?ordering information? on page 307 the avr is described in detail. figure 1-1. application diagram mcu atmel atmega328p lin bus lin-sbc atmel ata6630 atmel ata6614q
3 ata6614q [datasheet] 9240h?auto?10/14 2. pin configuration figure 2-1. pinning qfn48, 7mm 7mm table 2-1. pin description pin symbol function 1 pb5 port b 5 i/o line (sck / pcint5) 2 mcuavcc microcontroller adc-unit supply voltage (referred to as avcc pin in section 5. ?microcontroller block? on page 30 ) 3 adc6 adc input channel 6 4 aref analog reference voltage input 5 gnd ground 6 adc7 adc input channel 7 7 pc0 port c 0 i/o line (adc0/pcint8) 8 pc1 port c 1 i/o line (adc1/pcint9) 9 pc2 port c 2 i/o line (adc2/pcint10) 10 pc3 port c 3 i/o line (adc3/pcint11) 11 pc4 port c 4 i/o line (adc4/sda/pcint12) 12 pc5 port c 5 i/o line (adc5/scl/pcint13) 13 pc6 port c 6 i/o line (reset/pcint14) 14 pd0 port d 0 i/o line (rxd/pcint16) 15 pd1 port d 1 i/o line (txd/pcint17) 16 pd2 port d 2 i/o line (int0/pcint18) 17 (1) rxd receive data output 18 (1) inh high side switch output for controlling an external voltage regulator note: 1. this identifies the pins of the lin sbc ata6630 pb5 mcuavcc adc6 aref gnd4 adc7 pc0 pc1 pc2 pc3 pc4 pc5 mcuvcc gnd1 pd4 pd3 lin gnd wake ntrig en vs vcc pvcc pb4 pb3 pb2 pb1 pb0 pd7 pd6 pd5 pb7 pb6 mcuvcc gnd2 pc6 pd0 pd1 pd2 rxd inh txd nres wd_osc tm mode kl_15 1 48 47 46 45 44 43 42 41 40 39 38 37 13 14 15 16 17 18 19 20 21 22 23 24 2 3 4 5 6 7 8 9 10 11 12 36 35 34 33 32 31 30 29 28 27 26 25
ata6614q [datasheet] 9240h?auto?10/14 4 19 (1) txd transmit data input, active low output (strong pull down) 20 (1) nres watchdog and undervoltage reset output (open drain) 21 (1) wd_osc external resistor for adjustable watchdog timing 22 (1) tm tie to ground ? for factory use only 23 (1) mode connect to gnd for normal watchdog operation or connect to vcc for disabling the watchdog 24 (1) kl_15 ignition detection (edge sensitive) 25 (1) pvcc voltage regulator sense input 26 (1) vcc voltage regulator output 27 (1) vs battery supply voltage 28 (1) en enables the device into normal mode 29 (1) ntrig watchdog trigger input (negative edge) 30 (1) wake high voltage input for local wake-up request 31 (1) agnd analog system gnd 32 (1) lin lin bus input/output 33 pd3 port d 3 i/o line (int1 oc2b/pcint19) 34 pd4 port d 4 i/o line (t0/xck/pcint20) 35 gnd1 ground 36 mcuvcc microcontroller supply voltage (referred to as vcc pin in section 5. ?microcontroller block? on page 30 ) 37 gnd2 ground 38 mcuvcc microcontroller supply voltage (referred to as vcc pin in section 5. ?microcontroller block? on page 30 ) 39 pb6 port b 6 i/o line (tosc1/xtal1/pcint6) 40 pb7 port b 7 i/o line (tosc2/xtal2/pcint7) 41 pd5 port d 5 i/o line (t1/oc0b/pcint21) 42 pd6 port d 6 i/o line (ain0/oc0a pcint22) 43 pd7 port d 7 i/o line (ain1/pcint23) 44 pb0 port b 0 i/o line (icp1/clko/pcint0) 45 pb1 port b 1 i/o line (oc1a/pcint1) 46 pb2 port b 2 i/o line (oc1b/ss/pcint2) 47 pb3 port b 3 i/o line (mosi/oc2a/pcint3) 48 pb4 port b 4 i/o line (miso/pcint4) backside heat slug is connected to gnd table 2-1. pin description (continued) pin symbol function note: 1. this identifies the pins of the lin sbc ata6630
5 ata6614q [datasheet] 9240h?auto?10/14 3. absolute maximum ratings table 3-1. maximum ratings of the sip stresses beyond those listed under ?absolute maximum ratings? may cause permanent damage to the device. this is a stress rating only and functional operation of the device at these or any other conditions beyond t hose indicated in the operational sections of this specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability . parameters symbol min. typ. max. unit hbm esd ansi/esd-stm5.1 jesd22-a114 aec-q100 (002) 2 kv cdm esd stm 5.3.1 750 v machine model esd aec-q100-rev.f (003) 150 v esd according to ibee lin emc test spec. 1.0 following iec 61000-4-2 - pin vs, lin to gnd - pin wake (2.7k serial resistor) to gnd - kl_15 (47k /100nf) to gnd 8 kv esd hbm following stm5.1 with 1.5k 100pf - pin vs, lin, kl_15, wake to gnd 6 kv storage temperature t s ?55 +150 c operating temperature (1) t case ?40 +125 c thermal resistance junction to heat slug r thjc 5 k/w thermal resistance junction to ambient r thja 25 k/w thermal shutdown of vcc regulator 150 165 170 c thermal shutdown of lin output 150 165 170 c thermal shutdown hysteresis 10 c note: 1. t case means the temper ature of the heat slug (backside). it is ma ndatory that this ba ckside temperature is 125c in the application. table 3-2. maximum ratings of the lin-sbc stresses beyond those listed under ?absolute maximum ratings? may cause permanent damage to the device. this is a stress rating only and functional operation of the device at these or any other conditions beyond t hose indicated in the operational sections of this specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability . parameters symbol min. typ. max. unit supply voltage v s v s ?0.3 +40 v pulse time 500ms; t a = 25c output current i vcc 85ma v s +40 v pulse time 2min; t a =25c output current i vcc 85ma v s 27 v wake (with 2.7k serial resistor) kl_15 (with 47k /100nf) dc voltage transient voltage due to iso7637 (coupling 1nf) ?1 ?150 +40 +100 v v inh - dc voltage ?0.3 v s + 0.3 v lin - dc voltage ?27 +40 v
ata6614q [datasheet] 9240h?auto?10/14 6 logic pins (rxd, txd, en, nres, ntrig, wd_osc, mode, tm) ?0.3 vcc + 0.5 v output current nres i nres +2 ma pvcc dc voltage vcc dc voltage ?0.3 ?0.3 +5.5 +6.5 v v table 3-2. maximum ratings of the lin-sbc (continued) stresses beyond those listed under ?absolute maximum ratings? may cause permanent damage to the device. this is a stress rating only and functional operation of the device at these or any other conditions beyond t hose indicated in the operational sections of this specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability . parameters symbol min. typ. max. unit table 3-3. maximum ratings of the microcontroller stresses beyond those listed under ?absolute maximum ratings? may cause permanent damage to the device. this is a stress rating only and functional operation of the device at these or any other conditions beyond t hose indicated in the operational sections of this specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability . parameters symbol min. typ. max. unit voltage on any pin except reset with respect to ground ?0.5 mcuvcc + 0.5 v voltage on reset with respect to ground ?0.5 13.0 v maximum operating voltage 6.0 v dc current per i/o pin 40.0 ma dc current mcuvcc and gnd pins 200.0 ma injection current at mcuvcc = 0v (1) 5.0 ma injection current at mcuvcc = 5v 1.0 ma note: 1. maximum current per port = 30ma
7 ata6614q [datasheet] 9240h?auto?10/14 4. lin system-basis-chip block 4.1 features master and slave operation possible supply voltage up to 40v operating voltage v s = 5v to 27v typically 10a supply current during sleep mode typically 35a supply current in silent mode linear low-drop voltage regulator, 85ma current capability: normal, fail-safe, and silent mode v cc = 5.0v 2% in sleep mode v cc is switched off vcc undervoltage detection (4ms reset time) and watchdog reset logical combined at open drain output nres negative trigger input for watchdog adjustable watchdog time via external resistor boosting the voltage regulator possibl e with an external npn transistor lin physical layer according to lin 2.0, 2.1 and saej2602-2 wake-up capability via lin-bus, wake pin, or kl_15 pin inh output to control an external voltage regulat or or to switch off the master pull up resistor txd time-out timer bus pin is overtemperature and short-ci rcuit protected versus gnd and battery advanced emc and esd performance fulfills the oem ?hardware requirements for lin in automotive applications rev.1.1? interference and damage protection according to iso7637 4.2 description the atmel ? ata6630 is a fully integrated li n transceiver, which complies with the lin 2.0, 2.1 and saej2602-2 specifications. it has a low-drop voltage regulator for 5v/85ma output and a window watchdog. the voltage regulator is able to source up to 85ma, but the output current can be boosted by using an external npn transistor. the atmel ata6630 is designed to handle the low-speed data communication in vehicl es, e.g., in convenience electronics. improved slope control at the lin-driver ensures secure data communication up to 20kbaud. sleep mode and silent mode guarantee very low current consumption.
ata6614q [datasheet] 9240h?auto?10/14 8 figure 4-1. block diagram sbc adjustable watchdog oscillator short circuit and overtemperature protection txd time-out timer edge detection debounce time internal testing unit control unit slew rate control wake-up bus timer mode select undervoltage reset normal/silent/ fail-safe mode 5v rf filter watchdog out rxd gnd ntrig pvcc pvcc pvcc tm mode en txd kl_15 wake receiver - + normal mode normal and fail-safe mode lin wd_osc nres pvcc vcc vs inh
9 ata6614q [datasheet] 9240h?auto?10/14 4.3 functional description 4.3.1 physical layer compatibility since the lin physical layer is independent from higher lin laye rs (e.g., the lin protocol layer), all nodes with a lin physica l layer according to revision 2.x can be mixe d with lin physical layer nodes, which are, according to older versions (i.e., lin 1.0, lin 1.1, lin 1.2, lin 1.3), withou t any restrictions. 4.3.2 supply pin (vs) the lin operating voltage is v s = 5v to 27v. an undervoltage detection is implemented to disable data transmission if v s falls below vs th in order to avoid false bus messages. after switching on vs, the ic starts in fail-safe mode, and the voltage regulator is switched on (5v/85ma output capability). the supply current is typically 10a in sleep mode and 35a in silent mode. 4.3.3 ground pin (gnd) the ic does not affect the lin bus in th e event of gnd disconnection. it is able to handle a ground shift up to 11.5% of versus the mandatory system ground is pin 5. 4.3.4 voltage regulator output pin (vcc) the internal 3.3v/5v voltage regulator is capable of driving l oads up to 50ma. it is able to supply the microcontroller and other ics on the pcb and is protected against overloads by means of current limitation and overtemperatur e shut-down. furthermore, the output voltage is monitored and will cause a reset signal at th e nres output pin if it drops below a defined threshold v thun . to boost up the maximum load current, an external np n transistor may be used, with its base connected to the vcc pin and its emitter connected to pvcc. 4.3.5 voltage regulator sense pin (pvcc) the pvcc is the sense input pin of the 5v voltage regulator. for normal applications (i.e., when only using the internal output transistor), this pin must be connected to the vcc pin. if an external boosting transistor is used, the pvcc pin must be connected to the output of this tr ansistor, i.e., its emitter terminal. 4.3.6 bus pin (lin) a low-side driver with internal current lim itation and thermal shutdown and an internal pull-up resistor compliant with the lin 2.x specification are implement ed. the allowed voltage range is between ?27v and +40v. reverse currents from the lin bus to vs are suppressed, even in the event of gnd shifts or battery disconnection. lin receiver thresholds are compatible with the lin protocol specification. the fa ll time from recessive to dominant bus st ate and the rise time from dominant to recessive bus state are slope controlled. 4.3.7 input/output pin (txd) in normal mode the txd pin is the microcont roller interface used to control the stat e of the lin output. txd must be pulled to ground in order to have a low lin-bus. if txd is high or not co nnected (internal pull-up resistor), the lin output transistor i s turned off, and the bus is in recessive state. during fail-saf e mode, this pin is used as output and is signalling the fail-saf e source (together with the rxd output). it is current-limited to < 8ma. 4.3.8 txd dominant time-out function the txd input has an internal pull-up resistor. an internal timer prevents the bus line from being driven permanently in dominant state. if txd is forc ed to low for longer than t dom > 27ms, the lin-bus driver is switched to recessive state. nevertheless, when switching to sleep mode, th e actual level at the txd pin is relevant. to reactivate the lin bus driver , switch txd to high (> 10s).
ata6614q [datasheet] 9240h?auto?10/14 10 4.3.9 output pin (rxd) this output pin reports the state of the lin-bus to the microcontro ller. lin high (recessive state) is reported by a high level at rxd; lin low (dominant state) is reported by a low level at rx d. the output has an internal pull-up resistor with typically 5k to pvcc. the ac characteristics can be defined with an external load capacitor of 20pf. the output is short-circuit pr otected. rxd is switched off in unpowered mode (i.e., v s = 0v). during fail-safe mode it is signalling the fail- safe source (together with the txd- pin). 4.3.10 enable input pin (en) the enable input pin controls th e operation mode of the device. if en is high, the circuit is in normal mode, with transmission paths from txd to lin and from lin to rxd both active. the vcc voltage regulator op erates with 5v/85ma output capability. if en is switched to low while txd is still high, the device is forced to silent mode. no data tr ansmission is then possible, a nd the current consumptio n is reduced to i vssilent typ. 35a. the vcc regulator has its full functionality. if en is switched to low while txd is low, the device is fo rced to sleep mode. no data transmission is possible, and the voltage regulator is switched off. 4.3.11 wake input pin (wake) the wake input pin is a high-voltage input used to wake up the device from sleep mode or silent mode. it is usually connected to an external switch in the application to generate a local wake-up. a pull-up current source, typically 10a, is implemented. if a local wake-up is not needed in the applicat ion, connect the wake pin directly to the vs pin. 4.3.12 mode input pin (mode) connect the mode pin directly or via an external resistor to gnd for normal watc hdog operation. to debug the software of the connected microcontroller, connect the mode pin to vcc and the watchdog is switched off. 4.3.13 tm input pin the tm pin is used for final production measurements at atmel ? . in normal application, it has to be always connected to gnd. 4.3.14 kl_15 pin the kl_15 pin is a high-voltage input used to wake up the device from sleep or silent mode. it is an edge-sensitive pin (low- to-high transition). it is usually connected to ignition to gen erate a local wake-up in the application when the ignition is switched on. although kl_15 pin is at high voltage (v batt) , it is possible to switch the ic into sleep or silent mode. connect the kl_15 pin directly to gnd if you do not need it. a debounce timer with a typical tdb kl_15 of 160s is implemented. the input voltage threshold can be adjusted by varyin g the external resistor due to the input current i kl_15 . to protect this pin against voltage transients, a serial resistor of 47k and a ceramic capacitor of 100nf are recommended. with this rc combination you can increase the wake-up time tw kl_15 and, therefore, the sensitivit y against transients on the ignition kl_15. the wake-up time can also be increased by using external capacitors with higher values. 4.3.15 inh output pin the inh output pin is used to switch on an external voltage regulator during norma l and fail-safe mode. the inh output is a high-side switch, which is switched-off in sleep and si lent mode. it is possible to switch off the external 1k master resistor via the inh pin for master node applications. 4.3.16 wake-up events from sleep or silent mode lin-bus wake pin en pin kl_15
11 ata6614q [datasheet] 9240h?auto?10/14 4.3.17 reset output pin (nres) the reset output pin, an open drain output, switches to low during vcc undervoltage or a watchdog failure. 4.3.18 wd_osc output pin the wd_osc output pin provides a typical voltage of 1.2v, wh ich supplies an external resistor with values between 34k and 120k to adjust the watchdog oscillator time. 4.3.19 ntrig input pin the ntrig input pin is the trigger input for the window watchdog. a pu ll-up resistor is implemented. a negative edge triggers the watchdog. the trigger signal (low) must exceed a minimum time t trigmin to generate a watchdog trigger. 4.4 modes of operation figure 4-2. modes of operation table 4-1. table of modes mode of operation transceiver pin lin vcc pin mode watchdog pin wd_osc pin inh unpowered off recessive on gnd on on off fail-safe off recessive 5v gnd on 1.23v on normal on txd depending 5v gnd on 1.23v on silent off recessive 5v gnd off 0v off sleep off recessive 0v gnd off 0v off unpowered mode v batt = 0v a: v s > 5v b: v s < 4v c: bus wake-up event d: wake up from wake or kl_15 pin fail-safe mode normal mode vcc: 5v with undervoltage monitoring communication: on watchdog : on vcc: 5v with undervoltage monitoring communication : off watchdog : on silent mode vcc: 5v with undervoltage monitoring communication: off watchdog : off sleep mode vcc: switched off communication: off watchdog: off go to silent command a txd = 0 en = 0 txd = 1 en = 0 en = 1 en = 1 en = 1 b b b c + d + e e c + d b local wake-up event go to sleep command e: nres switches to low
ata6614q [datasheet] 9240h?auto?10/14 12 4.4.1 normal mode this is the normal transmitting and receiving mode. the vo ltage regulator is active and can source up to 85ma. the undervoltage detection is activated. the watchdog needs a trigger signal from ntrig to avoid resets at nres. if nres is switched to low, the ic changes its state to fail-safe mode. 4.4.2 silent mode a falling edge at en when txd is high switches the ic into silent mode. the txd signal has to be logic high during the mode select window (see figure 4-3 on page 12 ). the transmission path is disabled in silent mode. the inh output is switched off and the voltage divider is ena bled. the overall supply current from v batt is a combination of the i vssi = 35a plus the vcc regulator output current i vcc . the 5v regulator with 2% tolerance can source up to 85ma . the internal slave termination between the lin pin and the vs pin is disabled in silent mode to minimize the current consum ption in the event that the lin pin is short-circuited to gnd. only a weak pull-up current (typically 10 a) between the lin pin and the vs pin is present. silent mode can be activated independently from the actual level on the lin, wake, or kl _15 pins. if an undervoltage condition occurs, nres is switched to low and the ic changes its state to fail-safe mode. a voltage lower than the lin pre_wake detection vlinl at the lin pin activates the internal lin receiver and starts the wake-up detection timer. figure 4-3. switch to silent mode delay time silent mode t d _sleep = maximum 20s mode select window lin switches directly to recessive mode t d = 3.2s lin vcc nres txd en normal mode silent mode
13 ata6614q [datasheet] 9240h?auto?10/14 a falling edge at the lin pin followed by a dominant bus level maintained for a certain time period (>t bus ) and followed by a rising edge at the lin pin (see figure 4-4 on page 13 ) result in a remote wake-up request which is only possible if txd is high. the device switches from silent mode to fail-safe mode. t he internal lin slave terminatio n resistor is switched on. the remote wake-up request is indicated by a low level at the rxd pin to interrupt the microcontroller (see figure 4-4 on page 13 ). en high can be used to switch directly to normal mode. figure 4-4. lin wake up from silent mode watchdog off start watchdog lead time t d watchdog undervoltage detection active silent mode 5v fail safe mode 5v normal mode low fail-safe mode normal mode en high node in silent mode high high nres en vcc voltage regulator rxd lin bus bus wake-up filtering time t bus txd
ata6614q [datasheet] 9240h?auto?10/14 14 4.4.3 sleep mode a falling edge at en when txd is low switches the ic into sleep mode. the txd signal has to be logic low during the mode select window ( figure 4-5 on page 14 ). in order to avoid any influence to the li n-pin during switching into sleep mode it is possible to switch the en up to 3.2s earlier to low than th e txd. therefore, the best an easiest way are two falling edges at txd and en at the same time. the transmission pa th is disabled in sleep mode. the supply current i vssleep from v batt is typically 10a. the inh output and the vcc regulator are switched off. nres and rxd are low. the internal slave termination between the lin pin and vs pin is disabled to minimize the current consumpt ion in the event that the lin pi n is short-circuited to gnd. only a weak pull-up current (typically 10 a) between the lin pin and the vs pin is present. sleep mode can be activated independently from the current level on the lin, wake, or kl_15 pin. a voltage lower than the lin pre_wake detection vlinl at the lin pin activates the internal lin receiver and starts the wake-up detection timer. figure 4-5. switch to sleep mode delay time sleep mode t d_sleep = maximum 20s lin switches directly to recessive mode t d = 3.2s lin vcc nres txd en sleep mode normal mode mode select window
15 ata6614q [datasheet] 9240h?auto?10/14 a falling edge at the lin pin followed by a dominant bus level maintained for a certain time period (>t bus ) and a rising edge at pin lin result in a remote wake-up request. the de vice switches from sleep mode to fail-safe mode. the vcc regulator is activated, and the internal lin slave te rmination resistor is switched on. the remote wake-up re-quest is indicated by a low level at the rxd pin to interrupt the microcontroller (see figure 4-6 on page 15 ). en high can be used to switch directly from sleep/silent to fail-safe mode. if en is st ill high after vcc ramp up and undervoltage reset time, the ic switches to the normal mode. figure 4-6. lin wake up from sleep mode regulator wake-up time off state on state low fail-safe mode normal mode en high microcontroller start-up time delay reset time watchdog nres en vcc voltage regulator rxd lin bus bus wake-up filtering time t bus txd watchdog off start watchdog lead time t d
ata6614q [datasheet] 9240h?auto?10/14 16 4.4.4 sleep or silent mode: behavior at a floating lin-bus or a short circuited lin to gnd in sleep or in silent mode the device has a very low current consumption even during short-circ uits or floating conditions on the bus. a floating bus can arise if the mast er pull-up resistor is missing, e.g., if it is switched off when the lin-master is in sleep mode or even if the power supply of the master node is switched off. in order to minimize the current consumption i vs in sleep or silent mode during volt age levels at the lin-pin below the lin pre-wake threshold, the receiver is activated only for a specific time t mon . if t mon elapses while the voltage at the bus is lower than the pre-wake detection low (v linl ) and higher than the lin domin ant level, the receiver is switched off again and the circuit changes back to sleep respectively sile nt mode. the current consumption is then i vssleep_short or i vssilent_short (typ. 10a more than i vssleep respectively i vssilent ). if a dominant state is r eached on the bus no wake-up will occur. even if the voltage rises above the pre-wake detection high (v linh ), the ic will stay in sleep respectively silent mode (see figure 4-7 ). this means the lin-bus must be above the pre-wake detection threshold vlinh for a few microseconds before a new lin wake-up is possible. figure 4-7. floating lin-bus during sleep or silent mode i vssleep/silent i vssleep / i vssilent i vsfail i vssilent_short i vssleep_short / v busdom v linl i vs t mon lin pre-wake lin dominant state lin bus mode of operation int. pull-up resistor rlin wake-up detection phase off (disabled) sleep/silent mode sleep/silent mode
17 ata6614q [datasheet] 9240h?auto?10/14 if the atmel ? ata6630 is in sleep or silent mode and the vo ltage level at the lin-bus is in dominant state (v lin < v busdom ) for a time period exceeding t mon (during a short circuit at lin, for example), the ic switches back to sleep mode respectively silent mode. the v s current consumption then is i vssleep_short or i vssilent_short (typ. 10a more than i vssleep respectively i vssilent ). after a positive edge at pin lin the ic s witches directly to fail-safe mode (see figure 4-8 on page 17 ). figure 4-8. short circuit to gnd on the lin bus during sleep- or silent mode 4.4.5 fail-safe mode the device automatically switches to fail-safe mode at system power-up. the voltage regulator is switched on (see figure 4-12 on page 21 ). the nres output switches to low for t res = 4ms and gives a reset to the microcontroller. the lin communication is switched off. the ic stays in this mode until en is switched to high. the ic then changes to normal mode. a power down of v batt (v s < vs thu ) during silent or sleep mode switches the ic into fail-safe mode after power up. a low level at nres switches into fail-safe mode directly. during fail -safe mode, the txd pin is an output and signals the fail-safe source (together wit h the rxd output). the lin sbc can operate in different modes, like normal, silent, or sleep mode. the func tionality of these modes is described in table 4-2 . a wake-up event from either silent or sleep mode will be si gnalled to the microcontroller using the two pins rxd and txd. the coding is shown in table 4-3 on page 18 . a wake-up event will lead the ic to the fail-safe mode. sleep/silent mode i vssleep/silent i vsfail i vssilent_short i vssleep_short / v busdom v linl lin pre-wake lin dominant state lin bus i vs mode of operation int. pull-up resistor rlin off (disabled) on (enabled) wake-up detection phase sleep/silent mode fail-safe mode t mon t mon table 4-2. txd, rxd depending from operation modes different modes txd rxd fail-safe mode signalling fail-safe sources (see table 4-3 ) normal mode follows data transmission silent mode high high
ata6614q [datasheet] 9240h?auto?10/14 18 4.4.6 unpowered mode after the battery voltage has been connected to the application circuit, the voltage at the vs pin increases according to the block capacitor (see figure 4-11 on page 21 ). after vs is higher than the vs undervoltage threshold v sthf , the ic mode changes from unpowered mode to fail-safe mode. the vcc output voltage reaches its nominal value after t vcc . this time, t vcc , depends on the externally applied vcc capacitor and the load. the nres is low for the reset time delay t reset . during this time, t reset , no mode change is possible. the behavior of vcc, nres and vs is shown in figure 4-9 (ramp up): figure 4-9. vcc and nres versus vs (ramp up) table 4-3. signalling fail-safe sources fail-safe sources txd rxd lin wake-up (pin lin) low low local wake-up (at pin wake, pin kl_15) low high vs th (battery) undervoltage detection high low table 4-4. signalling in fail-safe mode after a reset (nres was low), shows the reset source at txd and rxd pins fail-safe source txd rxd vcc undervoltage high low watchdog reset high high unpowered mode v (v) 6.5 7.0 6.0 5.5 5.0 4.5 4.0 3.5 3.0 2.5 2.0 1.5 1.0 0.5 0 0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 vs (v) nres vcc vs
19 ata6614q [datasheet] 9240h?auto?10/14 figure 4-10. vcc and nres versus vs (ramp down) please note that the upper graphs are only valid if the vs ra mp up and ramp down-time is much slower than the vcc ramp up time t vcc and the nres delay time t reset . if during sleep or silent mode the voltage level of v s drops below the undervoltage detection threshold v sthu , the ic switches into unpowered mode. if during normal mode the voltage level of v s drops below the undervoltage detection threshold v sthu , the ic switches into fail-safe mode, this means the lin transceiver is disabled in order to avoid malfunctions or false bus messages. 4.5 wake-up scenarios from silent or sleep mode 4.5.1 remote wake-up via dominant bus state a voltage lower than the lin pre_wake detection v linl at the lin pin activates the internal lin receiver and starts the wake- up detection timer. a falling edge at the lin pin followed by a dominant bus level v busdom maintained for a certain time period (>t bus ) and followed by a rising edge at pin lin result in a remote wake-up request. a remote wake-up from silent mode is only possible if txd is high. the device switches from silent or sleep mode to fail-safe m ode. the vcc voltage regulator is/remains activated, the inh pin is switched to high, and the internal slave termination resistor is switched on. the remote wake-up request is indicated by a low level at t he rxd pin to generate an interrupt for the mi crocontroller and a strong pull down at txd. 4.5.2 local wake-up via pin wake a falling edge at the wake pin fo llowed by a low level maintain ed for a certain time period (>t wake ) results in a local wake-up request. the device switches to fail-safe mode. the internal slave termination resistor is switched on. the local wake-up request is indicated by a low level at t he txd pin to generate an interrupt for the mi crocontroller. when the wake pin is low, it is possible to switch to silent or sleep mode via pin en. in this case, the wake-up signal has to be switched to high > 10s before the negative edge at wake star ts a new local wake-up request. 4.5.3 local wake-up via pin kl_15 a positive edge at pin kl_15 followed by a high voltage level for a certain time period (> t kl_15 ) results in a local wake-up request. the device switches into the fail-safe mode. the inte rnal slave termination resistor is switched on. the extra long wake-up time ensures that no transients at kl_15 create a wake- up. the local wake-up request is indicated by a low level at the txd pin to generate an interrupt for the microcontroller. during high-level voltage at pin kl_15, it is possible to switch to silent or sleep mode via pin en. in this case, the wake-up si gnal has to be switched to low > 250s before the positive edge at kl_15 starts a new local wake-up request. with ex ternal rc combination, the time is even longer. v (v) 6.5 7.0 6.0 5.5 5.0 4.5 4.0 3.5 3.0 2.5 2.0 1.5 1.0 0.5 0 7.0 6.5 6.0 5.5 5.0 4.5 4.0 3.5 3.0 2.5 2.0 1.5 1.0 0.5 0 vs (v) vs unpowered mode nres vcc
ata6614q [datasheet] 9240h?auto?10/14 20 4.5.4 wake-up source recognition the device can distinguish between different wake-up sources. the wake-up source can be read on the txd and rxd pin in fail-safe mode. these flags are immediately reset if the microcontroller sets the en pin to high (see figure 4-4 on page 13 and figure 4-6 on page 15 ) and the ic is in normal mode. 4.5.5 fail-safe features during a short-circuit at lin to v battery , the output limits the output current to i bus_lim . due to the power dissipation, the chip temperature exceeds t linoff , and the lin output is switched off. the chip cools down and after a hysteresis of t hys , switches the output on again. rxd stays on high bec ause lin is high. during lin overtemperature switch-off, the vcc regulator works independently. during a short-circuit from lin to gnd the ic can be switc hed into sleep or silent mode and even in this case the current consumption is lower than 30a in sleep mode and lower than 70a in silent mode. if the short-circuit disappears, the ic starts with a remote wake-up. sleep or silent mode: during a floating c ondition on the bus the ic switches back to sleep mode/silent mode automatically and thereby the current consumption is lower than 30a/70a. the reverse current is < 2a at the li n pin during loss of vbatt. this is optim al behavior for bus systems where some slave nodes are supplied from battery or ignition. during a short circuit at vcc, the ou tput limits the output current to i vcclim . because of undervoltage, nres switches to low and the ic switches into fail-safe mo de. if the chip temperature exceeds the value t vccoff , the vcc output switches off. the chip cools down and after a hysteresis of t hys , switches the output on agai n. because of the fail- safe mode, the vcc voltage will switch on again althoug h en is switched off from the microcontroller. the microcontroller can start with its normal operation. en pin provides a pull-down resistor to force the tr ansceiver into recessive mode if en is disconnected. rxd pin is set floating if v batt is disconnected. txd pin provides a pull-up resistor to force the tr ansceiver into recessive mode if txd is disconnected. if txd is short-circuited to gnd, it is possible to switch to sleep mode via enable. after switching the lin transceiver into normal mode the txd pin must be pulled to high longer than 10s in order to activate the lin driver. this feature prevents the bus from being driven into dominant state when the ic is switched into normal mode and txd is low. if the wd_osc pin has a short-circuit to gnd and the ntri g signal has a period time > 27ms a reset is guaranteed. if the resistor at the wd_osc pin is disconnected and the ntrig signal has a period time < 46ms a reset is guaranteed. if there is no ntrig signal and a short-circuit at wd_osc to gnd the nres switches to low after 90ms. for an open circuit (no resistor) at wd_osc it switches to low after 390ms.
21 ata6614q [datasheet] 9240h?auto?10/14 4.6 voltage regulator the voltage regulator needs an external capacitor for compensation and for smoothing the disturbances from the microcontroller. it is recommended to us e an electrolythic capacitor with c 1.8f and a ceramic capacitor with c = 100nf. the values of these capacitors can be vari ed by the customer, depending on the application. the main power dissipation of the ic is created from the vcc output current i vcc , which is needed for the application. figure 4-11. vcc voltage regulator: ramp-up and undervoltage detection figure 4-12. power dissipation: safe operating area: vcc output current versus supply voltage vs at different ambient temperatures for programming purposes of the microcontro ller it is potentially necessary to supp ly the vcc output via an external power supply while the vs pin of the system basis chip is disconnec ted. this behavior will not af fect the system basis chip. nres 5v t t t vs 5v v thun t res_f t reset t vcc 5.5v 12v vcc i vcc (ma) 90 80 70 60 50 40 30 20 10 0 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 v s (v) t amb = 105c t amb = 110c t amb = 115c t amb = 100c
ata6614q [datasheet] 9240h?auto?10/14 22 4.7 watchdog the watchdog anticipates a trigger signal from the microcon troller at the ntrig (negative edge) input within a time window of t wd . the trigger signal must exceed a minimum time t trigmin > 200ns. if a triggering signal is not received, a reset signal will be generated at output nres. after a watchdog reset the ic starts with the lead time. the timing basis of the watchdog is provided by the internal oscillator. its time period, t osc , is adjustable via the external resistor r wd_osc (34k to 120k ). during silent or sleep mode the watchdog is switched off to reduce current consumption. the minimum time for the first watchdog pulse is required afte r the undervoltage reset at nres disappears. it is defined as lead time t d . after wake up from sleep or silent mode, the lead time t d starts with the negativ e edge of the rxd output. 4.7.1 typical timing sequence with r wo_osc = 51k the trigger signal twd is adjustable between 20ms and 64ms using the external resistor r wd_osc . for example, with an ex ternal resistor of r wd_osc = 51k 1%, the typical parameters of the watchdog are as follows: t osc = 0.405 r wd_osc ? 0.0004 (r wd_osc ) 2 (r wd_osc in k ; t osc in s) t osc = 19.6 s due to 51k t d = 7895 19.6 s = 155ms t 1 = 1053 19.6 s = 20.6ms t 2 = 1105 19.6 s = 21.6ms t nres = constant = 4ms after ramping up the battery voltage, the 5v regulator is switched on. the reset output nr es stays low for the time t reset (typically 4ms), then it switc hes to high, and the watchdog waits for the trigge r sequence from the microcontroller. the lead time, t d , follows the reset and is t d = 155ms. in this time, the first watchdog pulse from the microcontroller is required. if the trigger pulse ntrig occurs during this time, the time t 1 starts immediately. if no trigger signal occurs during the time t d , a watchdog reset with t nres = 4ms will reset the mi crocontroller after t d = 155ms. the times t 1 and t 2 have a fixed relationship. a triggering signal from the microcontrolle r is anticipated within the time frame of t 2 = 21.6ms. to avoid false triggering from glitches, the trigger pulse must be longer than t trig,min > 200ns. this slope serves to re start the watchdog sequence. if the triggering signal fails in this open window t 2 , the nres output will be drawn to ground. a triggering signal during the closed window t 1 immediately switches nres to low. figure 4-13. timing sequence with r wd_osc =51k t nres = 4ms undervoltage reset watchdog reset t reset = 4ms t trig > 200ns t 1 = 20.6ms t 2 = 21ms t 2 t 1 t wd t d = 155ms vcc 5v ntrig nres
23 ata6614q [datasheet] 9240h?auto?10/14 4.7.2 worst case calculation with r wo_osc = 51k the internal oscillator has a tolera nce of 20%. this means that t 1 and t 2 can also vary by 20%. the worst case calculation for the watchdog period t wd is calculated as follows. the ideal watchdog time t wd is between the maximum t 1 and the minimum t 1 plus the minimum t 2 . t 1,min = 0.8 t 1 = 16.5ms, t 1 ,max = 1.2 t 1 = 24.8ms t 2,min = 0.8 t 2 = 17.3ms, t 2 ,max = 1.2 t 2 = 26ms t wdmax = t 1min + t 2min = 16.5ms + 17.3ms = 33.8ms t wdmin = t 1max = 24.8ms t wd = 29.3ms 4.5ms (15%) a microcontroller with an oscillator tolerance of 15% is sufficient to supply the trigger inputs correctly. table 4-5. typical watchdog timings rosc/k t osc / s t d /ms t 1 /ms t 2 /ms t wd /ms t nres /ms 34 13.3 105 14.0 14.7 19.9 4 51 19.61 154.80 20.64 21.67 29.32 4 91 33.54 264.80 35.32 37.06 50.14 4 120 42.84 338.22 45.32 47.34 64.05 4
ata6614q [datasheet] 9240h?auto?10/14 24 4.8 electrical characteristics 5v < v s < 27v, ?40c < t j < 150c, unless otherwise specified. all values refer to gnd pins no. parameters test conditions pin symbol min. typ. max. unit type* 1 vs pin 1.1 nominal dc voltage range vs v s 5 27 v a 1.2 supply current in sleep mode sleep mode v lin > v s ? 0.5v v s < 14v vs i vssleep 3 10 14 a a sleep mode, v lin = 0v bus shorted to gnd v s < 14v vs i vssleep_short 6 20 30 a a 1.3 supply current in silent mode bus recessive v s < 14v without load at vcc vs i vssilent 20 35 50 a a silent mode v s < 14v bus shorted to gnd without load at vcc vs i vssilent_short 25 45 70 a a 1.4 supply current in normal mode bus recessive v s < 14v without load at vcc vs i vsrec 0.3 0.8 ma a 1.5 supply current in normal mode bus recessive v s < 14v v cc load current 50ma vs i vsdom 50 53 ma a 1.6 supply current in fail-safe mode bus recessive, rxd is low v s < 14v without load at vcc vs i vsfail 1.5 2.0 ma a 1.7 vs undervoltage threshold switch to unpowered mode vs v sthu 3.7 4.2 4.7 v a switch to fail-safe mode vs v sthf 4.0 4.5 5.0 v a 1.8 vs undervoltage threshold hysteresis vs v sth_hys 0.3 v a 2 rxd output pin 2.1 low-level output sink current normal mode v lin = 0v v rxd = 0.4v rxd i rxd 1.3 2.5 8 ma a 2.2 low-level output voltage i rxd = 1ma rxd v rxdl 0.4 v a 2.3 internal resistor to pvcc rxd r rxd 3 5 7 k a 3 txd input/output pin 3.1 low-level voltage input txd v txdl ?0.3 +0.8 v a 3.2 high-level voltage input txd v txdh 2 v cc + 0.3v v a 3.3 pull-up resistor v txd = 0v txd r txd 125 250 400 k a 3.4 high-level leakage current v txd = v cc txd i txd ?3 +3 a a 3.5 low-level output sink current fail-safe mode, wake up v lin = v s v wake = 0v v txd = 0.4v txd i txdwake 2 2.5 8 ma a *) type means: a = 100% tested, b = 100% correlation test ed, c = characterized on samples, d = design parameter
25 ata6614q [datasheet] 9240h?auto?10/14 4 en input pin 4.1 low-level voltage input en v enl ?0.3 +0.8 v a 4.2 high-level voltage input en v enh 2 v cc + 0.3v v a 4.3 pull-down resistor v en = v cc en r en 50 125 200 k a 4.4 low-level input current v en = 0v en i en ?3 +3 a a 5 ntrig watchdog input pin 5.1 low-level voltage input ntrig v ntrigl -0.3 +0.8 v a 5.2 high-level voltage input ntrig v ntrigh 2 v cc + 0.3v v a 5.3 pull-up resistor v ntrig = 0v ntrig r ntrig 125 250 400 k a 5.4 high-level leakage current v ntrig = v cc ntrig i ntrig -3 +3 a a 6 mode input pin 6.1 low-level voltage input mode v model ?0.3 +0.8 v a 6.2 high-level voltage input mode v modeh 2 v cc + 0.3v v a 6.3 high-level leakage current v mode = v cc or v mode = 0v mode i mode ?3 +3 a a 7 inh output pin 7.1 high-level voltage i inh = ?15ma inh v inhh v s ? 0.75 v s v a 7.2 switch-on resistance between vs and inh inh r inh 30 50 a 7.3 leakage current sleep mode v inh = 0v/27v, vs = 27v inh i inhl ?3 +3 a a 8 lin bus driver 8.1 driver recessive output voltage load1/load2 lin v busrec 0.9 v s v s v a 8.2 driver dominant voltage v vs = 7v r load = 500 lin v _losup 1.2 v a 8.3 driver dominant voltage v vs = 18v r load = 500 lin v _hisup 2 v a 8.4 driver dominant voltage v vs = 7.0v r load = 1000 lin v _losup_1k 0.6 v a 8.5 driver dominant voltage v vs = 18v r load = 1000 lin v _hisup_1k 0.8 v a 8.6 pull-up resistor to vs the serial diode is mandatory lin r lin 20 30 47 k a 8.7 voltage drop at the serial diodes in pull-up path with r slave i serdiode = 10ma lin v serdiode 0.4 1.0 v d 8.8 lin current limitation v bus = v batt_max lin i bus_lim 70 120 200 ma a 4.8 electrical characteristics (continued) 5v < v s < 27v, ?40c < t j < 150c, unless otherwise specified. all values refer to gnd pins no. parameters test conditions pin symbol min. typ. max. unit type* *) type means: a = 100% tested, b = 100% correlation test ed, c = characterized on samples, d = design parameter
ata6614q [datasheet] 9240h?auto?10/14 26 8.9 input leakage current at the receiver including pull- up resistor as specified input leakage current driver off v bus = 0v v batt = 12v lin i bus_pas_do m ?1 ?0.35 ma a 8.10 leakage current lin recessive driver off 8v < v batt < 18v 8v < v bus < 18v v bus v batt lin i bus_pas_rec 10 20 a a 8.11 leakage current at gnd loss, control unit disconnected from ground. loss of local ground must not affect communication in the residual network. gnd device = v s v batt = 12v 0v < v bus < 18v lin i bus_no_gnd ?10 +0.5 +10 a a 8.12 leakage current at loss of battery. node has to sustain the current that can flow under this condition. bus must remain operational under this condition. v batt disconnected v sup_device = gnd 0v < v bus < 18v lin i bus_no_bat 0.1 2 a a 8.13 capacitance on pin lin to gnd lin c lin 20 pf d 9 lin bus receiver 9.1 center of receiver threshold v bus_cnt = (v th_dom + v th _ rec )/2 lin v bus_cnt 0.475 v s 0.5 v s 0.525 v s v a 9.2 receiver dominant state v en = v cc lin v busdom 0.4 v s v a 9.3 receiver recessive state v en = v cc lin v busrec 0.6 v s v a 9.4 receiver input hysteresis v hys = v th_rec ? v th_dom lin v bushys 0.028 v s 0.1 v s 0.175 v s v a 9.5 pre_wake detection lin high-level input voltage lin v linh v s ? 2v v s + 0.3v v a 9.6 pre_wake detection lin low-level input voltage activates the lin receiver lin v linl ?27 v s ? 3.3v v a 10 internal timers 10.1 dominant time for wake-up via lin bus v lin = 0v lin t bus 30 90 150 s a 10.2 time delay for mode change from fail-safe into normal mode via en pin v en = v cc en t norm 5 15 20 s a 10.3 time delay for mode change from normal mode to sleep mode via en pin v en = 0v en t sleep 2 7 12 s a 10.4 txd dominant time-out time v txd = 0v txd t dom 27 55 70 ms a 10.5 time delay for mode change from silent mode into normal mode via en v en = v cc en t s_n 5 15 40 s a 4.8 electrical characteristics (continued) 5v < v s < 27v, ?40c < t j < 150c, unless otherwise specified. all values refer to gnd pins no. parameters test conditions pin symbol min. typ. max. unit type* *) type means: a = 100% tested, b = 100% correlation test ed, c = characterized on samples, d = design parameter
27 ata6614q [datasheet] 9240h?auto?10/14 10.6 monitoring time for wake- up over lin bus lin t mon 6 10 15 ms a lin bus driver ac paramete r with different bus loads load 1 (small): 1nf, 1k ; load 2 (large): 10nf, 500 ; r rxd = 5k ; c rxd = 20pf; load 3 (medium): 6.8nf, 660 characterized on samples; 10.7 and 10.8 spec ifies the timing parameters for proper operation at 20kbit/s, 10.9 a nd 10.10 at 10.4kbit/s 10.7 duty cycle 1 th rec(max) = 0.744 v s th dom(max) = 0.581 v s v s = 7.0v to 18v t bit = 50s d1 = t bus_rec(min) /(2 t bit ) lin d1 0.396 a 10.8 duty cycle 2 th rec(min) = 0.422 v s th dom(min) = 0.284 v s v s = 7.6v to 18v t bit = 50s d2 = t bus_rec(max) /(2 t bit ) lin d2 0.581 a 10.9 duty cycle 3 th rec(max) = 0.778 v s th dom(max) = 0.616 v s v s = 7.0v to 18v t bit = 96s d3 = t bus_rec(min) /(2 t bit ) lin d3 0.417 a 10.10 duty cycle 4 th rec(min) = 0.389 v s th dom(min) = 0.251 v s v s = 7.6v to 18v t bit = 96s d4 = t bus_rec(max) /(2 t bit ) lin d4 0.590 a 10.11 slope time falling and rising edge at lin v s = 7.0v to 18v lin t slope_fall t slope_rise 3.5 22.5 s a 11 receiver electrical ac parameters of the lin physical layer lin receiver, rxd load conditions (crxd): 20pf 11.1 propagation delay of receiver ( figure 4-14 on page 29 ) v s = 7.0v to 18v t rx_pd = max(t rx_pdr , t rx_pdf ) rxd t rx_pd 6 s a 11.2 symmetry of receiver propagation delay rising edge minus falling edge v s = 7.0v to 18v t rx_sym = t rx_pdr ? t rx_pdf rxd t rx_sym ?2 +2 s a 12 nres open drain output pin 12.1 low-level output voltage v s 5.5v i nres = 1ma nres v nresl 0.14 v a 12.2 low-level output low 10k to 5v v cc = 0v nres v nresll 0.14 v a 12.3 undervoltage reset time v s 5.5v c nres = 20pf nres 2 4 6 ms a 12.4 reset debounce time for falling edge v s 5.5v c nres = 20pf nres t res_f 1.5 10 s a 12.5 switch off leakage current v nres = 5.5v nres ?3 +3 a a 4.8 electrical characteristics (continued) 5v < v s < 27v, ?40c < t j < 150c, unless otherwise specified. all values refer to gnd pins no. parameters test conditions pin symbol min. typ. max. unit type* *) type means: a = 100% tested, b = 100% correlation test ed, c = characterized on samples, d = design parameter
ata6614q [datasheet] 9240h?auto?10/14 28 13 watchdog oscillator 13.1 voltage at wd_osc in normal or fail-safe mode i wd_osc = ?200a v vs 4v wd_os c v wd_osc 1.13 1.23 1.33 v a 13.2 possible values of resistor resistor 1% wd_os c r osc 34 120 k a 13.3 oscillator period r osc = 34k t osc 10.65 13.3 15.97 s a 13.4 oscillator period r osc = 51k t osc 15.68 19.6 23.52 s a 13.5 oscillator period r osc = 91k t osc 26.83 33.5 40.24 s a 13.6 oscillator period r osc = 120k nres t osc 34.2 42.8 51.4 s a 14 watchdog timing relative to t osc 14.1 watchdog lead time after reset t d 7895 cycles a 14.2 watchdog closed window t 1 1053 cycles a 14.3 watchdog open window t 2 1105 cycles a 14.4 watchdog reset time nres t nres 3.2 4 4.8 ms a 15 kl_15 pin 15.1 high-level input voltage r v = 47k positive edge initializes a wake-up kl_15 v kl_15h 4 v s + 0.3v v a 15.2 low-level input voltage r v = 47k kl_15 v kl_15l ?1 +2 v a 15.3 kl_15 pull-down current v s < 27v v kl_15 = 27v kl_15 i kl_15 50 60 a a 15.4 internal debounce time without extern al capacitor kl_15 tdb kl_15 80 160 250 s a 15.5 kl_15 wake-up time r v = 47k , c = 100nf kl_15 tw kl_15 0.4 2 4.5 ms c 16 wake pin 16.1 high-level input voltage wake v wakeh v s ? 1v v s + 0.3v v a 16.2 low-level input voltage initializes a wake-up signal wake v wakel ?1 v s ? 3.3v v a 16.3 wake pull-up current v s < 27v, v wake = 0v wake i wake ?30 ?10 a a 16.4 high-level leakage current v s = 27v, v wake = 27v wake i wakel ?5 +5 a a 16.5 time of low pulse for wake-up via wake pin v wake = 0v wake i wakel 30 70 150 s a 17 vcc voltage regulator in normal/ fail-safe and silent mode, vcc and pvcc shortcircuited 17.1 output voltage vcc 5.5v < v s < 18v (0ma to 50ma) vcc vcc nor 4.9 5.1 v a 5.5v < v s < 18v (0ma to 85ma) vcc vcc nor 4.9 5.1 v c 17.2 output voltage vcc at low vs 4v < v s < 5.5v vcc vcc low v s ? v d 5.1 v a 17.3 regulator drop voltage v s > 4v, i vcc = ?20ma vs, vcc v d1 250 mv a 17.4 regulator drop voltage v s > 4v, i vcc = ?50ma vs, vcc v d2 400 600 mv a 17.5 regulator drop voltage v s > 3.3v, i vcc = ?15ma vs, vcc v d3 200 mv a 17.6 line regulation 5.5v < v s < 18v vcc vcc line 0.1 0.2 % a 4.8 electrical characteristics (continued) 5v < v s < 27v, ?40c < t j < 150c, unless otherwise specified. all values refer to gnd pins no. parameters test conditions pin symbol min. typ. max. unit type* *) type means: a = 100% tested, b = 100% correlation test ed, c = characterized on samples, d = design parameter
29 ata6614q [datasheet] 9240h?auto?10/14 figure 4-14. definition of bus timing characteristics 17.7 load regulation 5ma < i vcc < 50ma at 100khz vcc vcc load 0.1 0.5 % a 17.8 power supply ripple rejection 10hz to 100khz c vcc = 10f v s = 14v, i vcc = ?15ma vcc 50 db d 17.9 output current limitation vs > 5.5v vcc i vcclim ?240 ?130 ?85 ma a 17.10 external load capacity 0.2 < esr < 5 at 100khz for phase margin 60 vcc c load 1.8 10 f d esr < 0.2 at 100khz for phase margin 30 17.11 vcc undervoltage threshold referred to vcc v s > 5.5v vcc v thunn 4.2 4.8 v a 17.12 hysteresis of undervoltage threshold referred to vcc v s > 5.5v vcc vhys thun 250 mv a 17.13 ramp-up time v s > 5.5v to v cc = 5v c vcc = 2.2f i load = ?5ma at vcc vcc t vcc 370 600 s a 4.8 electrical characteristics (continued) 5v < v s < 27v, ?40c < t j < 150c, unless otherwise specified. all values refer to gnd pins no. parameters test conditions pin symbol min. typ. max. unit type* *) type means: a = 100% tested, b = 100% correlation test ed, c = characterized on samples, d = design parameter txd (input to transmitting node) vs (transceiver supply of transmitting node) rxd (output of receiving node1) rxd (output of receiving node2) lin bus signal thresholds of receiving node1 thresholds of receiving node2 t bus_rec(max) t rx_pdr(1) t rx_pdf(2) t rx_pdr(2) t rx_pdf(1) t bus_dom(min) t bus_dom(max) th rec(max) th dom(max) th rec(min) th dom(min) t bus_rec(min) t bit t bit t bit
ata6614q [datasheet] 9240h?auto?10/14 30 5. microcontroller block 5.1 features high performance, low power avr ? 8-bit microcontroller advanced risc architecture 131 powerful instructions ? mo st single clock cycle execution 32 x 8 general purpose working registers fully static operation up to 20mips throughput at 20mhz on-chip 2-cycle multiplier high endurance non-volatile memory segments 32kbytes of in-system self-progr ammable flash program memory 1kbyte eeprom 2kbytes internal sram write/erase cycles: 10,000 flash/100,000 eeprom optional boot code section with independent lock bits in-system programming by on-chip boot program true read-while-write operation programming lock for software security peripheral features two 8-bit timer/counters with separate prescaler and compare mode one 16-bit timer/counter with separate prescaler, compare mode, and capture mode real time counter with separate oscillator six pwm channels 8-channel 10-bit adc temperature measurement programmable serial usart master/slave spi serial interface byte-oriented 2-wire serial interface (philips i 2 c compatible) programmable watchdog timer with separate on-chip oscillator on-chip analog comparator interrupt and wake-up on pin change special microcontroller features power-on reset and programmable brown-out detection internal calibrated oscillator external and internal interrupt sources six sleep modes: idle, adc noise reduction, powe r-save, power-down, standby, and extended standby i/o 23 programmable i/o lines operating voltage: 2.7v - 5.5v for atmega328p temperature range: automotive temperature range: -40c to +125c speed grade: 0 - 8mhz at 2.7 - 5.5v (automotiv e temp. range: -40c to +125c) 0 - 16mhz at 4.5 - 5.5v (automotive temp. range: -40c to +125c)
31 ata6614q [datasheet] 9240h?auto?10/14 low-power consumption active mode: 1.5ma at 3v - 4mhz power-down mode: 1a at 3v 5.2 overview the atmega328p is a low-power cmos 8- bit microcontroller based on the avr ? enhanced risc architecture. by executing powerful instructions in a single clock cycle, the atmega328p achieves throughputs approaching 1 mips per mhz allowing the system designer to optimize power consumption versus processing speed. 5.2.1 block diagram figure 5-1. block diagram power supervision por/bod and reset oscillator circuits/ clock generation watchdog timer watchdog oscillator program logic debugwire avr cpu eeprom data bus flash gnd vcc a/d conv. 8-bit t/c 0 16-bit t/c 1 analog comparator internal bandgap 8-bit t/c 2 usart 0 spi twi 2 6 port d (8) port b (8) port c (7) sram avcc aref gnd reset xtal[1..2] pd[0..7] pb[0..7] pc[0..6] adc[6..7]
ata6614q [datasheet] 9240h?auto?10/14 32 the avr ? core combines a rich instruction set with 32 general purp ose working registers. all t he 32 registers are directly connected to the arithmetic logic unit (alu), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. the resulti ng architecture is more code efficient while achieving throughputs up to ten times faster than conventional cisc microcontrollers. the atmega328p provides the following features: 32kbytes of in-system progr ammable flash with read-while-write capabilities, 1kbyte eeprom, 2kbytes sram, 23 general purpose i/o lines, 32 general purpose working registers, three flexible timer/counters with compare modes, internal and exte rnal interrupts, a serial programmable usart, a byte-oriented 2-wire serial interface, an spi serial port, a 8-channel 10-bit adc, a programmable watchdog timer with internal oscillator, and five software selectable power saving modes. the idle mode stops the cpu while allowing the sram, timer/counters, usart, 2-wire serial interface, spi port, and in terrupt system to continue f unctioning. the power-down mode saves t he register contents but freezes the os cillator, disabling all other chip functions until the next interrupt or hardware reset. in power-sa ve mode, the asynchronous timer continues to run, allowing the user to maintain a timer base while the rest of the device is sleeping. the adc noise reduction mode stops the cpu and al l i/o modules except asynchronous timer and adc, to minimize switching noise during adc conversions. in standby m ode, the crystal/resonator oscillat or is running while the rest of the device is sleeping. this allows very fast start-up combined with low power consumption. the device is manufactured using atmel ? ?s high density non-volatile memory technology. the on-chip isp flash allows the program memory to be reprogrammed in-system through an spi serial interface, by a conventional non-volatile memory programmer, or by an on-chip boot program running on the avr core. the boot program can use any interface to download the application program in the application flash memory. software in the boot flash section will continue to run while the application flash section is updated, providing true read-whi le-write operation. by combining an 8-bit risc cpu with in- system self-programmable flash on a monolithic chip, the atmel atm ega328p is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications. the atmega328p avr is supported with a full suite of prog ram and system development t ools including: c compilers, macro assemblers, program debugger/simulators, in-circuit emulators, and evaluation kits. 5.3 resources a comprehensive set of development to ols, application notes and datasheet s are available for download on http://www.at mel.com/avr. 5.4 data retention reliability qualification results show that the projected data retention failure rate is much less than 1 ppm over 20 years at 85c or 100 years at 25c. 5.5 about code examples this documentation contains simple code examples that briefly show how to use various parts of the device. these code examples assume that the part sp ecific header file is included before compilation. be aware that not all c compiler vendors include bit definitions in the header files and interrupt h andling in c is compiler depende nt. please conf irm with the c compiler documentation for more details. for i/o registers located in extended i/o map, ?in?, ?out?, ?sbis?, ? sbic?, ?cbi?, and ?sbi? instru ctions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?.
33 ata6614q [datasheet] 9240h?auto?10/14 5.6 avr cpu core 5.6.1 overview this section discusses the avr ? core architecture in general. the main function of the cpu core is to ensure correct program execution. the cpu must therefore be able to acce ss memories, perform calculations, control peripherals, and handle interrupts. figure 5-2. block diagram of the avr architecture in order to maximize performance and parallelism, the avr uses a harvard arch itecture ? with separate memories and buses for program and data. instructions in the program memo ry are executed with a single level pipelining. while one instruction is being executed, the next in struction is pre-fetched from the program memory. this co ncept enables instructions to be executed in every clock cycle. the program memory is in-system reprogrammable flash memory. the fast-access register file contains 32 x 8-bit general purpose working regi sters with a single clock cycle access time. this allows single-cycle arithmetic logic unit (alu) operation. in a typical alu operat ion, two operands are output from the register file, the oper ation is executed, and the result is stored back in th e register file ? in one clock cycle. six of the 32 registers can be used as three 16-bit indirect address register pointers for data space addressing ? enabling efficient address calculations. one of the these address pointers c an also be used as an address pointer for look up tables in flash program memory. these added function registers are the 16 -bit x-, y-, and z-register, de scribed later in this section. status and control interrupt unit spi unit 32 x 8 general purpose registers alu data bus 8-bit data sram watchdog timer instruction register instruction decoder analog comparator eeprom i/o lines i/o module n control lines direct addressing indirect addressing i/o module 2 i/o module 1 program counter flash program memory
ata6614q [datasheet] 9240h?auto?10/14 34 the alu supports arithmetic and logic operat ions between registers or between a constant and a register. single register operations can also be executed in the alu. after an arithmetic operation, the status register is updated to reflect information about the result of the operation. program flow is provided by conditional and unconditional ju mp and call instructions, able to directly address the whole address space. most avr ? instructions have a single 16-bit word format. every program memory address contains a 16- or 32-bit instruction. program flash memory space is divided in two sections, the boot program section and the applic ation program section. both sections have dedicated lock bits for write and read/write protection. th e spm instruction that writ es into the application fla sh memory section must reside in the boot program section. during interrupts and subroutine calls, the return address prog ram counter (pc) is stored on the stack. the stack is effectively allocated in the general data sr am, and consequently the stack size is onl y limited by the total sram size and the usage of the sram. all user programs must initialize the sp in the reset routine (before subroutines or interrupts are executed). the stack pointer (sp) is read /write accessible in the i/o space. the data sram can easily be accessed through the five different addressing modes supported in the avr architecture. the memory spaces in the avr architecture are all linear and regular memory maps. a flexible interrupt module has its control registers in the i/o space with an additional global interrupt enable bit in the st atus register. all interrupts have a separate interrupt vector in th e interrupt vector table. the interrupts have priority in accord ance with their interrupt vector position. the lower the interrupt vector address, the higher the priority. the i/o memory space contains 64 addresses for cpu peripheral functions as control registers, spi, and other i/o functions. the i/o memory can be accessed directly, or as the data space lo cations following those of the register file, 0x20 - 0x5f. in addition, the atmega328p has extended i/o space from 0x 60 - 0xff in sram where only the st/sts/std and ld/lds/ldd instructions can be used. 5.6.2 alu ? arithmetic logic unit the high-performance avr alu operates in direct connection wi th all the 32 general purpose working registers. within a single clock cycle, arithmetic operations between general pu rpose registers or between a register and an immediate are executed. the alu operations are divided into three main ca tegories ? arithmetic, logica l, and bit-functions. some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format. see the ?instruction set? section for a detailed description. 5.6.3 status register the status register contains information about the result of the most rec ently executed arithmetic instruction. this information can be used for altering program flow in order to per form conditional operations. note that the status register is updated after all alu operations, as specifi ed in the instruction set reference. this will in many cases remove the need for using the dedicated compare instructions, re sulting in faster and more compact code. the status register is not automati cally stored when entering an interrupt r outine and restored when returning from an interrupt. this must be handled by software. 5.6.3.1 sreg ? avr status register the avr status register ? sreg ? is defined as: ? bit 7 ? i: global interrupt enable the global interrupt enable bit must be set for the interrupts to be enabled. the individual interrupt enable control is then performed in separate control registers. if the global interrupt enable register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. the i-bi t is cleared by hardware after an interrupt has occurred, and is set by the reti instruction to enable subs equent interrupts. the i-bit can also be se t and cleared by the application with the sei and cli instructions, as describ ed in the instruction set reference. bit 76543210 0x3f (0x5f) i t h s v n z c sreg read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
35 ata6614q [datasheet] 9240h?auto?10/14 ? bit 6 ? t: bit copy storage the bit copy instructions bld (bit load) and bst (bit store) us e the t-bit as source or destination for the operated bit. a bit from a register in the register file can be copied into t by th e bst instruction, and a bit in t can be copied into a bit in a register in the register f ile by the bld instruction. ? bit 5 ? h: half carry flag the half carry flag h indicates a half carry in some arithmetic operations. half carry is usef ul in bcd arithmetic. see the ?instruction set description? for detailed information. ? bit 4 ? s: sign bit, s = n v the s-bit is always an exclusive or between the negative fl ag n and the two?s complement overflow flag v. see the ?instruction set description? for detailed information. ? bit 3 ? v: two?s complement overflow flag the two?s complement overflow flag v supports two?s comple ment arithmetics. see the ?instruction set description? for detailed information. ? bit 2 ? n: negative flag the negative flag n indicates a negative result in an arithmetic or logic operation. see the ?ins truction set description? for detailed information. ? bit 1 ? z: zero flag the zero flag z indicates a zero result in an arithmetic or l ogic operation. see the ?instruction set description? for detailed information. ? bit 0 ? c: carry flag the carry flag c indicates a carry in an arithmetic or logi c operation. see the ?instruction set description? for detailed information. 5.6.4 general purpose register file the register file is optimized for the avr ? enhanced risc instruction set. in order to achieve the required performance and flexibility, the following in put/output schemes are supported by the register file: one 8-bit output operand and one 8-bit result input two 8-bit output operands and one 8-bit result input two 8-bit output operands and one 16-bit result input one 16-bit output operand an d one 16-bit result input
ata6614q [datasheet] 9240h?auto?10/14 36 figure 5-3 shows the structure of the 32 general purpose working registers in the cpu. figure 5-3. avr cpu general purpose working registers most of the instructions operating on the regi ster file have direct access to all regi sters, and most of them are single cycle instructions. as shown in figure 5-3 , each register is also assigned a data memory addr ess, mapping them directly into the first 32 locations of the user data space. although not being physically implemented as sram locations, this memory organization provides great flexibility in access of the registers, as the x- , y- and z-pointer registers can be set to index any register i n the file. 5.6.4.1 the x-register, y-register, and z-register the registers r26..r31 have some added functions to their general purpose usage. these registers are 16-bit address pointers for indirect addressing of the data space. the three i ndirect address registers x, y, and z are defined as described in figure 5-4 . figure 5-4. the x-, y-, and z-registers in the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement (see the instru ction set reference for details). 7 0 addr. r0 0x00 r1 0x01 r2 0x02 ? r13 0x0d general r14 0x0e purpose r15 0x0f working r16 0x10 registers r17 0x11 ? r26 0x1a x-register low byte r27 0x1b x-register high byte r28 0x1c y-register low byte r29 0x1d y-register high byte r30 0x1e z-register low byte r31 0x1f z-register high byte 15 xh xl 0 x-register 7 0 7 0 r27 (0x1b) r26 (0x1a) 15 yh yl 0 y-register 7 0 7 0 r29 (0x1d) r28 (0x1c) 15 zh zl 0 z-register 7 0 7 0 r31 (0x1f) r30 (0x1e)
37 ata6614q [datasheet] 9240h?auto?10/14 5.6.5 stack pointer the stack is mainly used for storing te mporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. note that the stack is implemented as growing from higher to lower memory locations. the stack pointer register always points to t he top of the stack. the stack pointer point s to the data sram stack area where the subroutine and interr upt stacks are located. a stack push command will decrease the stack pointer. the stack in the data sram must be def ined by the program before any subroutin e calls are executed or interrupts are enabled. initial stack pointer value equals the last address of the internal sram and the stack pointer must be set to point above start of the sram, see figure 5-8 on page 41 . see table 5-1 for stack pointer details. the avr ? stack pointer is implemented as two 8-bit registers in the i/o space. the number of bits actually used is implementation dependent. note that the data space in some impl ementations of the avr architec ture is so small that only spl is needed. in this case, the sph register will not be present. 5.6.5.1 sph and spl ? stack pointer high and stack pointer low register table 5-1. stack pointer instructions instruction stack pointer description push decremented by 1 data is pushed onto the stack call icall rcall decremented by 2 return address is pushed onto the stack with a subroutine call or interrupt pop incremented by 1 data is popped from the stack ret reti incremented by 2 return address is popped from the stack with return from subroutine or return from interrupt bit 151413121110 9 8 0x3e (0x5e) sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 sph 0x3d (0x5d) sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 spl 76543210 read/write r/w r/w r/w r/w r/w r/w r/w r/w r/wr/wr/wr/wr/wr/wr/wr/w initial value ramend ramend ramend ramend ramend ramend ramend ramend ramend ramend ramend ramend ramend ramend ramend ramend
ata6614q [datasheet] 9240h?auto?10/14 38 5.6.6 instruction execution timing this section describes the general access timi ng concepts for instruction execution. the avr ? cpu is driven by the cpu clock clk cpu , directly generated from the selected clock source for the chip. no internal clock division is used. figure 5-5 shows the parallel instruction fetches and instruction exec utions enabled by the harvard architecture and the fast- access register file concept. this is the basic pipelining co ncept to obtain up to 1mips per mhz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. figure 5-5. the parallel instructio n fetches and instruction executions figure 5-6 shows the internal timing concept for the register file. in a single clock cycle an alu operation using two register operands is executed, and the result is stored back to the destination register. figure 5-6. single cycle alu operation clk cpu 1st instruction fetch 1st instruction execute 2nd instruction fetch t1 t2 t3 t4 2nd instruction execute 3rd instruction fetch 3rd instruction execute 4th instruction fetch clk cpu t1 register operands fetch result write back alu operation execute total execution time t2 t3 t4
39 ata6614q [datasheet] 9240h?auto?10/14 5.6.7 reset and interrupt handling the avr ? provides several different interrupt sources. these interrupts and the separate reset vector each have a separate program vector in the program memory space. all in terrupts are assigned individual enable bits which must be written logic one together with the global interrupt enable bit in the status register in order to enable the interrupt. depend ing on the program counter value, interrupts may be automatica lly disabled when boot lock bits blb02 or blb12 are programmed. this feature improves software security. see section 5.27 ?memory programming? on page 262 for details. the lowest addresses in the program memory space are by default defined as the re set and interrupt vect ors. the complete list of vectors is shown in section 5.11 ?interrupts? on page 73 . the list also determines the priority levels of the different interrupts. the lower the addres s the higher is the priority level. reset has the highest priority, and next is int0 ? the external interrupt request 0. the interrupt vectors can be move d to the start of the boot flas h section by setting the ivsel bi t in the mcu control regi ster (mcucr). refer to section 5.11 ?interrupts? on page 73 for more information. the reset vector can also be moved to the start of the boot flas h section by programming the bootrst fuse, see section 5.26 ?boot loader support ? read-while-write self-programming? on page 250 . when an interrupt occurs, the global interrupt enable i-bit is cl eared and all interrupts are disabled. the user software can write logic one to the i-bit to enable nested interrupts. all enab led interrupts can then interrupt the current interrupt routi ne. the i-bit is automatically set when a return fr om interrupt instruction ? reti ? is executed. there are basically two types of interrupts. the first type is triggered by an event that sets the interrupt flag. for these interrupts, the program counter is vectored to the actual interru pt vector in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt flag. interrupt flags can also be cleared by writing a logic one to the flag bi t position(s) to be cleared. if an interrupt condition occurs while the corres ponding interrupt enable bit is cleared, the interr upt flag will be set and remembered until the inte rrupt is enabled, or the flag is cleared by software. similarly, if one or more interrupt conditions occur while the global interrupt enable bit is cleared, the corresponding interrupt flag(s) will be set an d remembered until the global interrupt enable bit is se t, and will then be executed by order of priority. the second type of interrupts will trigger as long as the interr upt condition is present. these interrupts do not necessarily have interrupt flags. if the interrupt condition disappears befo re the interrupt is enabled, the interrupt will not be triggere d. when the avr exits from an interrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served. note that the status regi ster is not automatically stored when entering an in terrupt routine, nor restored when returning from an interrupt routine. this must be handled by software. when using the cli instruction to disable interrupts, the inte rrupts will be immediately disabled. no interrupt will be execute d after the cli instruction, even if it occu rs simultaneously with the cli instruction. the following example shows how this can be used to avoid interrupts during the timed eeprom write sequence. assembly code example in r16, sreg ; store sreg value cli ; disable interrupts during timed sequence sbi eecr, eempe ; start eeprom write sbi eecr, eepe out sreg, r16 ; restore sreg value (i-bit) c code example char csreg; csreg = sreg; /* store sreg value */ /* disable interrupts during timed sequence */ _cli(); eecr |= (1< ata6614q [datasheet] 9240h?auto?10/14 40 when using the sei instruction to enable interrupts, the in struction following sei will be executed before any pending interrupts, as shown in this example. 5.6.7.1 interrupt response time the interrupt execution response for all the enabled avr ? interrupts is four clock cycles mi nimum. after four clock cycles the program vector address for the actual interr upt handling routine is exec uted. during this four cl ock cycle period, the program counter is pushed onto the stack. the vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. if an interrupt occurs du ring execution of a multi-cycle in struction, this inst ruction is completed before the interrup t is served. if an interrupt occurs when the mcu is in sleep mode, the interrupt execution response time is increased by four clock cycles. this increase comes in addition to the start-up time from the selected sleep mode. a return from an interrupt hand ling routine takes four clock cycl es. during these four clock cycl es, the program counter (two bytes) is popped back from the stack, the stack pointer is incremented by two, and the i-bit in sreg is set. 5.7 avr memories 5.7.1 overview this section describes the different memo ries in the atmega328p. the avr architec ture has two main memory spaces, the data memory and the program memory space. in addit ion, the atmega328p features an eeprom memory for data storage. all three memory spaces are linear and regular. 5.7.2 in-system reprogrammable flash program memory the atmega328p contains 32kbyt es on-chip in-system reprogrammable flash me mory for program storage. since all avr instructions are 16 or 32 bits wide, t he flash is organized as 16k x 16. for soft ware security, the flash program memory space is divided into two sections, boot loader section and application program section in atmega328p. see selfprgen description in section 5.25.3.1 ?spmcsr ? store program memo ry control and status register? on page 249 and 261 for more details. the flash memory has an endurance of at least 10,000 wr ite/erase cycles. the atmega328p program counter (pc) is 14 bits wide, thus addressing the 16k program memory locations. the operation of boot program section and associated boot lock bits for software protection are described in detail in section 5.25 ?self-programming the flash, atmega328p? on page 243 and section 5.26 ?boot loader support ? read-while-write self-programming? on page 250 . section 5.27 ?memory programming? on page 262 contains a detailed description on flash programming in spi or parallel programming mode. constant tables can be allocated within the entire progra m memory address space (see t he lpm ? load program memory instruction description). timing diagrams for instruction fetc h and execution are presented in section 5.6.6 ?instruction execution timing? on page 38 . assembly code example sei ; set global interrupt enable sleep ; enter sleep, waiting for interrupt ; note: will enter sleep before any pending interrupt(s) c code example __enable_interrupt(); /* set global interrupt enable */ __sleep(); /* enter sleep, waiting for interrupt */ /* note: will enter sleep before any pending interrupt(s) */
41 ata6614q [datasheet] 9240h?auto?10/14 figure 5-7. program memory map atmega328p 5.7.3 sram data memory figure 5-8 shows how the atmega328p sram memory is organized. the atmega328p is a complex microcontroller with more perip heral units than can be suppo rted within the 64 locations reserved in the opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. the lower 2303 data memory locations address both the regi ster file, the i/o memory, extended i/o memory, and the internal data sram. the first 32 locations address the register file, the next 64 lo cation the standard i/o memory, then 160 locations of extended i/o memory, and the next 204 8 locations address the internal data sram. the five different addressing modes for the data memory cover: direct, indirect with displacement , indirect, indirect with pre- decrement, and indirect with post-increment. in the register file , registers r26 to r31 feature the indirect addressing pointer registers. the direct addressing reaches the entire data space. the indirect with displacement mode reaches 63 address locati ons from the base address given by the y- or z-register. when using register indirect addressing modes with automatic pre-decrement and post-increment, the address registers x, y, and z are decremented or incremented. the 32 general purpose working registers, 64 i/o registers, 1 60 extended i/o registers, and the 2048 bytes of internal data sram in the atmega328p are all accessible through all t hese addressing modes. the register file is described in section 5.6.4 ?general purpose register file? on page 35 . figure 5-8. data memory map 0x0000 0x3fff program memory application flash section boot flash section 32 registers 64 i/o registers 160 ext i/o registers data memory 0x0000 - 0x001f 0x0020 - 0x005f 0x0060 - 0x00ff 0x0100 0x08ff internal sram (2048 x 8)
ata6614q [datasheet] 9240h?auto?10/14 42 5.7.3.1 data memory access times this section describes the general access timing concepts for internal memory access. the in ternal data sram access is performed in two clk cpu cycles as described in figure 5-9 . figure 5-9. on-chip data sram access cycles 5.7.4 eeprom data memory the atmega328p contains 1k byte of dat a eeprom memory. it is organized as a s eparate data space, in which single bytes can be read and writ ten. the eeprom has an enduranc e of at least 100,000 write/er ase cycles. the access between the eeprom and the cpu is described in the following, specif ying the eeprom address re gisters, the eeprom data register, and the eeprom control register. section 5.27 ?memory programming? on page 262 contains a detailed description on eeprom programming in spi or parallel programming mode. 5.7.4.1 eeprom read/write access the eeprom access registers are accessible in the i/o space. the write access time fo r the eeprom is given in table 5-3 . a self-timing function, however, lets the user software detect when the next byte can be written. if t he user code contains instru ctions that write the eeprom , some precautions must be taken. in heavily filt ered power supplies, v cc is likely to rise or fall slowly on power-up/down. this causes the device for some period of time to run at a voltage lower than specified as minimum for the clock frequency used. see section 5.7.4.2 ?preventing eeprom corruption? on page 42 for details on how to avoid problems in these situations. in order to prevent unint entional eeprom writes, a specific wr ite procedure must be followed. refer to the descrip tion of the eeprom control register for details on this. when the eeprom is read, the cpu is halted for four clock cycles before the next instru ction is executed. when the eeprom is written, the cpu is ha lted for two clock cycles before the next instruction is executed. 5.7.4.2 preventing eeprom corruption during periods of low v cc, the eeprom data can be corrupted because the su pply voltage is too low for the cpu and the eeprom to operate properly. these issues are the same as for board level systems using eeprom, and the same design solutions should be applied. an eeprom data corruption can be caused by two situations when the voltage is too low. first, a regu lar write sequence to the eeprom requires a minimum vo ltage to operate correct ly. secondly, the cpu itself can ex ecute instructions incorrectly, if the supply voltage is too low. clk cpu t1 data data rd wr address valid compute address next instruction write read memory access instruction a ddress t2 t3
43 ata6614q [datasheet] 9240h?auto?10/14 eeprom data corruption can easily be avoided by following this design recommendation: keep the avr ? reset active (low) during periods of insufficient power supply volt age. this can be don e by enabling the internal brown-out detector (bod). if the detection level of the internal bod does not match the needed detection level, an external low v cc reset protection circuit can be used. if a reset o ccurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. 5.7.5 i/o memory the i/o space definition of the atmega328p is shown in section 5.30 ?register summary? on page 294 . all atmega328p i/os and peripherals are placed in the i/o spac e. all i/o locations may be accessed by the ld/lds/ldd and st/sts/std instructions, transferring data between the 32 general purpose working registers and the i/o space. i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be checked by usin g the sbis and sbic instructions. refer to the instruction set section for more details. when using the i/o specific comma nds in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega328p is a complex microcontroller with more peripheral units than can be supp orted within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. for compatibility with future devices, reserved bits should be wr itten to zero if accessed. re served i/o memory addresses should never be written. some of the status flags are cleared by writing a logical one to them. note tha t, unlike most other avrs, the cbi and sbi instructions will only operate on the spec ified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions work wit h registers 0x00 to 0x1f only. the i/o and peripherals control registers are explained in later sections. 5.7.5.1 general purpose i/o registers the atmega328p contains three general purpose i/o registers. these registers can be used for storing any information, and they are particularly useful for storin g global variables and status flags. genera l purpose i/o registers within the addres s range 0x00 - 0x1f are directly bit-accessible using the sbi, cbi, sbis, and sbic instructions. 5.7.6 register description 5.7.6.1 eearh and eearl ? the eeprom address register ? bits 15..9 ? res: reserved bits these bits are reserved bits in the atmega328p and will always read as zero. ? bits 8..0 ? eear8..0: eeprom address the eeprom address registers ? eea rh and eearl specify the eeprom a ddress in the 256 /512/512/1k bytes eeprom space. the eeprom data bytes are addressed linearly between 0 and 255/511/511/10 23. the initial value of eear is undefined. a proper value must be written before the eepr om may be accessed. eear8 is an unused bit in atmega328p and must always be written to zero. bit 151413121110 9 8 0x22 (0x42) ? ? ? ? ? ? ? eear8 eearh 0x21 (0x41) eear7 eear6 eear5 eear4 eear3 eear2 eear1 eear0 eearl 76543210 read/write r r r r r r r r/w r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 x xxxxxxxx
ata6614q [datasheet] 9240h?auto?10/14 44 5.7.6.2 eedr ? the eeprom data register ? bits 7..0 ? eedr7.0: eeprom data for the eeprom write operation, the eedr register contains th e data to be written to the eepr om in the address given by the eear register. for the eeprom read o peration, the eedr contains the data read out from the eeprom at the address given by eear. 5.7.6.3 eecr ? the eeprom control register ? bits 7..6 ? res: reserved bits these bits are reserved bits in the atmega328p and will always read as zero. ? bits 5, 4 ? eepm1 and eepm0: eeprom programming mode bits the eeprom programming mode bit setting defines which programming action that will be triggered when writing eepe. it is possible to program data in one atomic operation (erase th e old value and program the new value) or to split the erase and write operations in two differen t operations. the programming times for the different modes are shown in table 5-2 . while eepe is set, any write to eepmn will be ignored. during reset, the eepmn bits will be reset to 0b00 unless the eeprom is busy programming. ? bit 3 ? eerie: eeprom ready interrupt enable writing eerie to one enables the eeprom ready interrupt if the i bit in sreg is set. writin g eerie to zero disables the interrupt. the eeprom ready interrupt generates a cons tant interrupt when eepe is clea red. the interr upt will not be generated during eeprom write or spm. ? bit 2 ? eempe: eeprom master write enable the eempe bit determines whethe r setting eepe to one causes the eeprom to be written. when eempe is set, setting eepe within four clock cycles will write data to the eeprom at the selected add ress if eempe is zero, setting eepe will have no effect. when eempe has been written to one by software, hardware clears the bit to zero after four clock cycles. see the description of the eepe bi t for an eeprom write procedure. bit 76543210 0x20 (0x40) msb lsb eedr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x1f (0x3f) ? ? eepm1 eepm0 eerie eempe eepe eere eecr read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 x x 0 0 x 0 table 5-2. eeprom mode bits eepm1 eepm0 programming time operation 0 0 3.4ms erase and write in one operation (atomic operation) 0 1 1.8ms erase only 1 0 1.8ms write only 1 1 ? reserved for future use
45 ata6614q [datasheet] 9240h?auto?10/14 ? bit 1 ? eepe: eeprom write enable the eeprom write enable signal eepe is the write strobe to the eeprom. when address and data are correctly set up, the eepe bit must be written to one to write the value into the eeprom. the eempe bit must be written to one before a logical one is written to eepe, otherwise no eeprom write ta kes place. the following procedure should be followed when writing the eeprom (the order of steps 3 and 4 is not essential): 1. wait until eepe becomes zero. 2. wait until selfprgen in spmcsr becomes zero. 3. write new eeprom address to eear (optional). 4. write new eeprom data to eedr (optional). 5. write a logical one to the eempe bit while writing a zero to eepe in eecr. 6. within four clock cycles after setti ng eempe, write a logical one to eepe. the eeprom can not be programmed during a cpu write to the flash memory. the software must check that the flash programming is completed before initiating a new eeprom write. step 2 is only relevant if t he software contains a boot loader allowing the cpu to program the flash. if the flash is never being updated by the cpu, step 2 can be omitted. see section 5.26 ?boot loader support ? read-while-write self-programming? on page 250 for details about boot programming. caution: an interrupt between step 5 and step 6 will make the write cycle fail, since the eeprom master write enable will time-out. if an in terrupt routine accessing the eeprom is interrupting anothe r eeprom access, the eear or eedr register will be modified, causing the interrupted eeprom access to fail. it is recommended to have the global interrupt flag cleared during all the steps to avoid these problems. when the write access time has elapsed, the eepe bit is cleared by hardware. the user software can poll this bit and wait for a zero before wr iting the next byte. when eepe has be en set, the cpu is halted for two cycles before the ne xt instruction is executed. ? bit 0 ? eere: eeprom read enable the eeprom read enable signal eere is the read strobe to t he eeprom. when the correct address is set up in the eear register, the eere bit must be written to a logic one to trigger the eeprom read. the eeprom read access takes one instruction, and the reques ted data is available immediately. when the eeprom is read, the cpu is halted for four cycles before the next instru ction is executed. the user should poll the eepe bit before starting the read operatio n. if a write operation is in progress, it is neither possib le to read the eeprom, nor to change the eear register. the calibrated oscillator is used to time the eeprom accesses. table 5-3 lists the typical programming time for eeprom access from the cpu. the following code examples show one assembly and one c functi on for writing to the eeprom . the examples assume that interrupts are controlled (e.g. by disabling interrupts globa lly) so that no interrupts will occur during execution of the se functions. the examples also assume that no flash boot loader is present in the software. if such code is present, the eeprom write function must also wait for any ongoing spm command to finish. table 5-3. eeprom programming time symbol number of calibrated rc oscillator cycles typ programming time eeprom write (from cpu) 26.368 3.3ms
ata6614q [datasheet] 9240h?auto?10/14 46 assembly code example eeprom_write: ; wait for completion of previous write sbic eecr,eepe rjmp eeprom_write ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; write data (r16) to data register out eedr,r16 ; write logical one to eempe sbi eecr,eempe ; start eeprom write by setting eepe sbi eecr,eepe ret c code example void eeprom_write( unsigned int uiaddress, unsigned char ucdata) { /* wait for completion of previous write */ while(eecr & (1< 47 ata6614q [datasheet] 9240h?auto?10/14 the next code examples show assembly and c functions fo r reading the eeprom. the examples assume that interrupts are controlled so that no interrupts will o ccur during execution of these functions. 5.7.6.4 gpior2 ? general purpose i/o register 2 5.7.6.5 gpior1 ? general purpose i/o register 1 5.7.6.6 gpior0 ? general purpose i/o register 0 assembly code example eeprom_read: ; wait for completion of previous write sbic eecr,eepe rjmp eeprom_read ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; start eeprom read by writing eere sbi eecr,eere ; read data from data register in r16,eedr ret c code example unsigned char eeprom_read( unsigned int uiaddress) { /* wait for completion of previous write */ while(eecr & (1< ata6614q [datasheet] 9240h?auto?10/14 48 5.8 system clock and clock options 5.8.1 clock systems and their distribution figure 5-10 presents the principal clock systems in the avr ? and their distri bution. all of t he clocks need not be active at a given time. in order to reduce power consumption, the clo cks to modules not being used can be halted by using different sleep modes, as described in section 5.9 ?power management and sleep modes? on page 58 . the clock systems are detailed below. figure 5-10. clock distribution 5.8.1.1 cpu clock ? clk cpu the cpu clock is routed to parts of the system concerned with operation of the avr core. ex amples of such modules are the general purpose register file, the stat us register and the data memory holding t he stack pointer. halting the cpu clock inhibits the core from performing ge neral operations and calculations. 5.8.1.2 i/o clock ? clk i/o the i/o clock is used by the majority of the i/o modules, like timer/counters, spi, and usart. the i/o clock is also used by the external interrupt module, but note that some external interrupts are det ected by asynchronous logic, allowing such interrupts to be detected even if the i/o clock is halted. also note that start condition detecti on in the usi module is carrie d out asynchronously when clk i/o is halted, twi address recognition in all sleep modes. 5.8.1.3 flash clock ? clk flash the flash clock controls operation of the flash interface. the flash clock is usually active simultaneously with the cpu clock. 5.8.1.4 asynchronous timer clock ? clk asy the asynchronous timer clock allows the asynchronous timer/count er to be clocked directly from an external clock or an external 32 khz clock crystal. the dedicated clock domain allo ws using this timer/counter as a real-time counter even when the device is in sleep mode. asynchronous timer/counter flash and eeprom timer/counter oscillator calibrated rc oscillator low-frequency crystal oscillator crystal oscillator watchdog oscillator system clock prescaler general i/o modules avr clock control unit adc external clock cpu core source clock watchdog clock ram reset logic watchdog timer clk i/o clk asy clk cpu clk adc clk flash clock multiplexer
49 ata6614q [datasheet] 9240h?auto?10/14 5.8.1.5 adc clock ? clk adc the adc is provided with a dedicated clock do main. this allows halting the cpu and i/o clocks in order to reduce noise generated by digital circuitry. this give s more accurate adc conversion results. 5.8.2 clock sources the device has the following clock source options, selectable by fl ash fuse bits as shown below. the clock from the selected source is input to the avr ? clock generator, and routed to the appropriate modules. 5.8.2.1 default clock source the device is shipped with internal rc osc illator at 8.0mhz and with the fuse ck div8 programmed, resulting in 1.0mhz system clock. the startup time is set to maximum and time-out period enabled. (cksel = ?0010?, sut = ?10?, ckdiv8 = ?0?). the default setting ensures that all users can make their desired clock source setting using any available programming interface. 5.8.2.2 clock startup sequence any clock source needs a sufficient v cc to start oscillating and a minimum number of oscillating cycles before it can be considered stable. to ensure sufficient v cc , the device issues an internal reset with a time-out delay (t tout ) after the device reset is released by all other reset sources. section 5.10 ?system control and reset? on page 63 describes the start conditions for the internal reset. the delay (t tout ) is timed from the watchdog oscillator and the number of cycles in the delay is set by the sutx and ckselx fuse bits. the sele ctable delays are shown in table 5-5 . the frequency of the watchdog oscillator is voltage dependent as shown in section 5.29 ?typical characteristics? on page 287 . main purpose of the delay is to keep the avr in reset until it is supplied with minimum v cc . the delay will not monitor the actual voltage and it will be required to select a delay longer than the v cc rise time. if this is no t possible, an internal or external brown-out detection circuit should be used. a bod circuit will ensure sufficient v cc before it releases the reset, and the time-out delay can be disabled. dis abling the time-out delay without utilizin g a brown-out detection circuit is not recommended. the oscillator is required to oscillate for a minimum number of cycles before the clock is considered stable. an internal rippl e counter monitors the oscillator output clock, and keeps the internal reset active for a given number of clock cycles. the reset is then released and the device will start to execute. the re commended oscillator start-up time is dependent on the clock type, and varies from 6 cycles for an externally applied clock to 32k cycles for a low frequency crystal. the start-up sequence for the clock includes both the time-out delay and the start-up time wh en the device starts up from reset. when starting up from power-save or power-down mode, v cc is assumed to be at a sufficient level and only the start- up time is included. table 5-4. device clocking options select (1) device clocking option cksel3..0 low power crystal oscillator 1111 - 1000 full swing crystal oscillator 0111 - 0110 low frequency crystal oscillator 0101 - 0100 internal 128khz rc oscillator 0011 calibrated internal rc oscillator 0010 external clock 0000 reserved 0001 note: 1. for all fuses ?1? means unprogrammed while ?0? means programmed. table 5-5. number of watc hdog oscillator cycles typ time-out (v cc = 5.0v) typ time-out (v cc = 3.0v) number of cycles 0ms 0ms 0 4.1ms 4.3ms 512 65ms 69ms 8k (8,192)
ata6614q [datasheet] 9240h?auto?10/14 50 5.8.3 low power crystal oscillator pins xtal1 and xtal2 are input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillator, as shown in figure 5-11 on page 50 . either a quartz crystal or a ceramic resonator may be used. this crystal oscillator is a low power oscillator, with reduc ed voltage swing on the xtal2 output. it gives the lowest power consumption, but is not capable of driving other clock inputs, and may be more susceptible to noise in noisy environments. in these cases, refer to the section 5.8.4 ?full swing cr ystal oscillator? on page 51 . c1 and c2 should always be equal for both crystals and res onators. the optimal value of the capacitors depends on the crystal or resonator in use, t he amount of stray capacitance, and the electromagnetic noise of the environment. some initial guidelines for choosing capacitors for use with crystals are given in table 5-6 . for ceramic resonators , the capacitor values given by the manufacturer should be used. figure 5-11. crystal oscillator connections the low power oscillator can operate in three different modes, eac h optimized for a specific fr equency range. the operating mode is selected by the fuses cksel3..1 as shown in table 5-6 . notes: 1. this option should not be used with crystals, only with ceramic resonators. 2. if 8mhz frequency exceeds the specification of the device (depends on v cc ), the ckdiv8 fuse can be pro- grammed in order to divide the internal frequency by 8. it must be ensured that the resulting divided clock meets the frequency specif ication of the device. table 5-6. low power crystal oscillator operating modes (2) frequency range (mhz) recommended range for capacitors c1 and c2 (pf) cksel3..1 0.4 - 0.9 ? 100 (1) 0.9 - 3.0 12 - 22 101 3.0 - 8.0 12 - 22 110 8.0 - 16.0 12 - 22 111 c2 xtal2 (tosc2) xtal1 (tosc1) gnd c1
51 ata6614q [datasheet] 9240h?auto?10/14 the cksel0 fuse together with the sut1..0 fuses select the start-up times as shown in table 5-7 . notes: 1. these options should only be used when not opera ting close to the maximum frequency of the device, and only if frequency stability at start- up is not important for t he application. these options are not suitable for crystals. 2. these options are intended for use with ceramic resonator s and will ensure frequency st ability at start-up. they can also be used with crystals when not operating clos e to the maximum frequency of the device, and if fre- quency stability at start-up is not important for the application. 5.8.4 full swing crystal oscillator pins xtal1 and xtal2 are input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillator, as shown in figure 5-11 on page 50 . either a quartz crystal or a ceramic resonator may be used. this crystal oscillator is a full swing oscillator, with rail- to-rail swing on the xtal2 output. this is useful for driving oth er clock inputs and in noisy environments. the current consumption is higher than the section 5.8.3 ?low power crystal oscillator? on page 50 . note that the full swing crystal oscillator will only operate for v cc = 2.7 - 5.5v. c1 and c2 should always be equal for both crystals and res onators. the optimal value of the capacitors depends on the crystal or resonator in use, t he amount of stray capacitance, and the electromagnetic noise of the environment. some initial guidelines for choosing capacitors for use with crystals are given in table 5-9 on page 52 . for ceramic re sonators, the capacitor values given by the manufacturer should be used. the operating mode is selected by the fuses cksel3..1 as shown in table 5-8 . notes: 1. the frequency ranges are preliminary values. actual values are tbd. 2. if 8mhz frequency exceeds the specification of the device (depends on v cc ), the ckdiv8 fuse can be pro- grammed in order to divide the internal frequency by 8. it must be ensured that the resulting divided clock meets the frequency specif ication of the device. table 5-7. start-up times for the low po wer crystal oscillator clock selection oscillator source / power conditions start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1..0 ceramic resonator, fast rising power 258 ck 14ck + 4.1ms (1) 0 00 ceramic resonator, slowly rising power 258 ck 14ck + 65ms (1) 0 01 ceramic resonator, bod enabled 1k ck 14ck (2) 0 10 ceramic resonator, fast rising power 1k ck 14ck + 4.1ms (2) 0 11 ceramic resonator, slowly rising power 1k ck 14ck + 65ms (2) 1 00 crystal oscillator, bod enabled 16k ck 14ck 1 01 crystal oscillator, fast rising power 16k ck 14ck + 4.1ms 1 10 crystal oscillator, slowly rising power 16k ck 14ck + 65ms 1 11 table 5-8. full swing crystal oscillator operating modes (1) frequency range (1) (mhz) recommended range for capacitors c1 and c2 (pf) cksel3..1 0.4 - 16 12 - 22 011
ata6614q [datasheet] 9240h?auto?10/14 52 figure 5-12. crystal oscillator connections notes: 1. these options should only be used when not opera ting close to the maximum frequency of the device, and only if frequency stability at start- up is not important for t he application. these options are not suitable for crystals. 2. these options are intended for use with ceramic resonator s and will ensure frequency st ability at start-up. they can also be used with crystals when not operating clos e to the maximum frequency of the device, and if fre- quency stability at start-up is not important for the application. table 5-9. start-up times for the full sw ing crystal oscillator clock selection oscillator source / power conditions start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) cksel0 sut1..0 ceramic resonator, fast rising power 258 ck 14ck + 4.1ms (1) 0 00 ceramic resonator, slowly rising power 258 ck 14ck + 65ms (1) 0 01 ceramic resonator, bod enabled 1k ck 14ck (2) 0 10 ceramic resonator, fast rising power 1k ck 14ck + 4.1ms (2) 0 11 ceramic resonator, slowly rising power 1k ck 14ck + 65ms (2) 1 00 crystal oscillator, bod enabled 16k ck 14ck 1 01 crystal oscillator, fast rising power 16k ck 14ck + 4.1ms 1 10 crystal oscillator, slowly rising power 16k ck 14ck + 65ms 1 11 c2 xtal2 (tosc2) xtal1 (tosc1) gnd c1
53 ata6614q [datasheet] 9240h?auto?10/14 5.8.5 low frequency crystal oscillator the low-frequency crystal oscillator is optimized for use wi th a 32.768khz watch crystal. when selecting crystals, load capacitance and crystal?s equivalent series resistance, esr must be taken into consid eration. both values are specified by the crystal vendor. atmega328p oscillator is optimized for ve ry low power consumption, and thus when selecting crystals, see table 5-10 for maximum esr recommendations on 6.5pf, 9.0pf and 12.5pf crystals. note: 1. maximum esr is typical value based on characterization the low-frequency crystal oscillator provides an internal load capacitance of typica l 6pf at each tosc pin. the external capacitance (c) needed at each tosc pin can be calculated by using: where cl is the load capacitance for a 32.768khz crystal specified by the crystal vendor and c s is the total stray capacitance for one tosc pin. crystals specifying load capacitance (cl) higher than 6pf , require external capacitors applied as described in figure 5-11 on page 50 . the low-frequency crystal oscillator must be selected by se tting the cksel fuses to ?0110? or ?0111?, as shown in table 5- 12 . start-up times are determined by the sut fuses as shown in table 5-11 . note: 1. this option should only be used if frequency stab ility at start-up is not im portant for the application table 5-10. maximum esr recommendation for 32.768khz crystal crystal cl (pf) max esr [k ] (1) 6.5 75 9.0 65 12.5 30 table 5-11. start-up times for the low-freque ncy crystal oscillator clock selection sut1..0 additional delay from reset (v cc = 5.0v) recommended usage 00 4 ck fast rising power or bod enabled 01 4 ck + 4.1ms slowly rising power 10 4 ck + 65ms stable frequency at start-up 11 reserved table 5-12. start-up times for the low-freque ncy crystal oscillator clock selection cksel3..0 start-up time from power-down and power-save recommended usage 0100 (1) 1k ck 0101 32k ck stable frequency at start-up c2clc s ? =
ata6614q [datasheet] 9240h?auto?10/14 54 5.8.6 calibrated inte rnal rc oscillator by default, the internal rc oscillator provides an approxi mate 8.0mhz clock. though voltage and temperature dependent, this clock can be very accurate ly calibrated by the user. see table 5-128 on page 279 for more details. the device is shipped with the ckdiv8 fuse programmed. see section 5.8.11 ?system clock prescaler? on page 56 for more details. this clock may be selected as t he system clock by programming the cksel fuses as shown in table 5-13 . if selected, it will operate with no external components. duri ng reset, hardware loads the pre-programmed calibration value into the osccal register and thereby automat ically calibrates the rc oscillator. the accuracy of this calibration is shown as factory calibrati on in table 5-128 on page 279 . by changing the osccal register from sw, see section 5.8.12.1 ?osccal ? oscillator calibration register? on page 57 , it is possible to get a higher calibration accuracy than by using the factory calibration. the accuracy of this calibration is sho wn as user calibration in table 5-128 on page 279 . when this oscillator is used as the chip clock, the watchdog oscillator will still be used for the watchdog timer and for the reset time-out. for more information on the pre-programmed calibration value, see the section section 5.27.4 ?calibration byte? on page 265 . notes: 1. the device is shipped with this option selected. 2. if 8mhz frequency exceeds the specification of the device (depends on v cc ), the ckdiv8 fuse can be pro- grammed in order to divide the internal frequency by 8. when this oscillator is selected, start-up times are determined by the sut fuses as shown in table 5-14 on page 54 . note: 1. if the rstdisbl fuse is programmed, this start-up time will be increased to 14ck + 4.1 ms to ensure program- ming mode can be entered. 2. the device is shipped with this option selected. table 5-13. internal calibrated rc oscillator operating modes (1)(2) nominal frequency (mhz) cksel3..0 8 0010 table 5-14. start-up times for the internal calibrated rc oscillat or clock selection power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) sut1..0 bod enabled 6 ck 14ck (1) 00 fast rising power 6 ck 14ck + 4.1ms 01 slowly rising power 6 ck 14ck + 65 ms (2) 10 reserved 11
55 ata6614q [datasheet] 9240h?auto?10/14 5.8.7 128 khz internal oscillator the 128 khz internal oscillator is a low power oscillator prov iding a clock of 128khz. the frequency is nominal at 3v and 25c. this clock may be select as th e system clock by programming the cksel fuses to ?11? as shown in table 5-15 . . when this clock source is selected, start-up ti mes are determined by the sut fuses as shown in table 5-16 . note: 1. if the rstdisbl fuse is programmed, this start-up time will be increased to 14ck + 4.1ms to ensure program- ming mode can be entered. 5.8.8 external clock to drive the device from an external clock source, xtal1 should be driven as shown in figure 5-13 . to run the device on an external clock, the cksel fuses mu st be programmed to ?0000? (see table 5-17 ). figure 5-13. external clock drive configuration table 5-15. 128 khz internal oscillator operating modes nominal frequency cksel3..0 128khz 0011 table 5-16. start-up times for th e 128 khz internal oscillator power conditions start-up time from power-down and power-save additional delay from reset sut1..0 bod enabled 6 ck 14ck (1) 00 fast rising power 6 ck 14ck + 4ms 01 slowly rising power 6 ck 14ck + 64ms 10 reserved 11 table 5-17. crystal oscillator clock frequency frequency cksel3..0 0 - 20mhz 0000 xtal2 xtal1 gnd external clock signal nc
ata6614q [datasheet] 9240h?auto?10/14 56 when this clock source is selected, start-up ti mes are determined by the sut fuses as shown in table 5-18 . when applying an external clock, it is required to avoid s udden changes in the applied clock frequency to ensure stable operation of the mcu. a variati on in frequency of more than 2% from one clock cycle to the ne xt can lead to unpredictable behavior. if changes of more than 2% is required, ensur e that the mcu is kept in reset during the changes. note that the system clock prescaler can be used to implemen t run-time changes of the internal clock frequency while still ensuring stable operation. refer to section 5.8.11 ?system clock prescaler? on page 56 for details. 5.8.9 clock output buffer the device can output the system clock on the clko pin. to enable the output, the ckout fuse has to be programmed. this mode is suitable wh en the chip clock is used to driv e other circuits on the system. the clock also will be output during reset, and the normal operation of i/o pin will be overridden w hen the fuse is programmed. any clock source, including the internal rc oscillator, can be selected when the clock is out put on clko. if the system clock prescaler is used, it is the divided system clock that is output. 5.8.10 timer/counter oscillator atmega328p uses the same crystal oscillator for low- frequency oscillator and timer/counter oscillator. see section 5.8.5 ?low frequency crystal oscillator? on page 53 for details on the oscillator and crystal requirements. atmega328p share the timer/counter oscillator pins (tosc1 and tosc2) with xtal1 and xtal2. when using the timer/counter oscillator, the system clo ck needs to be four times the oscillator frequency. due to this and the pin sharing, the timer/counter oscillator can only be used when the calibrated in ternal rc oscillator is selected as system clock source. applying an external clock s ource to tosc1 can be done if extclk in the assr register is written to logic one. see section 5.17.9 ?asynchronous operation of timer/counter2? on page 148 for further description on selecting external clock as input instead of a 32.768khz watch crystal. 5.8.11 system clock prescaler the atmega328p has a system clock prescaler, and the system clock can be divided by setting the section 5.8.12.2 ?clkpr ? clock prescale register? on page 57 . this feature can be used to decrea se the system clock frequency and the power consumption when the requirement for processing power is low. this can be us ed with all clock source options, and it will affect the clock frequency of the cp u and all synchronous peripherals. clk i/o , clk adc , clk cpu , and clk flash are divided by a factor as shown in table 5-131 on page 280 . when switching between pr escaler settings, the system clock prescaler ensures that no glitches occurs in the clock system. it also ensures that no intermediate frequency is higher t han neither the clock frequency corresponding to the previous setting, nor the clock frequency corresponding to the new setti ng. the ripple counter that implements the prescaler runs at the frequency of the undivided clock, wh ich may be faster than the cpu's clock frequency. hence, it is not possible to determine the state of the presca ler - even if it were readable, and the exact time it takes to switch from one clock division to the other cannot be ex actly predicted. from the time the clkps values are written, it takes between t1 + t2 and t1 + 2 * t2 before the new clock frequency is active. in this interval, 2 acti ve clock edges are produced. here, t1 is the previous clock period, and t2 is the period corresponding to the new prescaler setting. to avoid unintentional c hanges of clock frequency, a spec ial write procedure must be fo llowed to chan ge the clkps bits: 1. write the clock prescaler change enable (clkpce) bit to one and all other bits in clkpr to zero. 2. within four cycles, write th e desired value to clkps while writing a zero to clkpce. interrupts must be disabled when changing prescaler setti ng to make sure the write pr ocedure is not interrupted. table 5-18. start-up times for th e external clock selection power conditions start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) sut1..0 bod enabled 6 ck 14ck 00 fast rising power 6 ck 14ck + 4.1ms 01 slowly rising power 6 ck 14ck + 65ms 10 reserved 11
57 ata6614q [datasheet] 9240h?auto?10/14 5.8.12 register description 5.8.12.1 osccal ? oscillator calibration register ? bits 7..0 ? cal7..0: osci llator calibration value the oscillator calibration register is used to trim the calibrated internal rc oscillat or to remove process variations from the oscillator frequency. a pre-programmed calibr ation value is automatically written to th is register during chip reset, giving th e factory calibrated frequency as specified in table 5-128 on page 279 . the application software can write this register to change the oscillator frequency. t he oscillator can be calibrated to frequencies as specified in table 5-128 on page 279 . calibration outside that range is not guaranteed. note that this oscillator is used to time eeprom and flash writ e accesses, and these write times will be affected accordingly. if the eeprom or flash are written, do no t calibrate to more than 8.8 mhz. other wise, the eeprom or flash write may fail. the cal7 bit determines the range of operat ion for the oscillator. setting this bit to 0 gives the lowest frequency range, setting this bit to 1 gives the highest frequency range. the two frequency ranges are overlapping, in other words a setting of osccal = 0x7f gives a higher frequency than osccal = 0x80. the cal6..0 bits are used to tune the frequency within the selected range. a setting of 0x00 gives the lowest frequency in that range, and a setting of 0x7f gives the highest frequency in the range. 5.8.12.2 clkpr ? clock prescale register ? bit 7 ? clkpce: clock prescaler change enable the clkpce bit must be written to logic one to enable cha nge of the clkps bits. the clkpce bit is only updated when the other bits in clkpr are simultaneously written to zero. clkpce is cleared by hardware four cycles after it is written or when clkps bits are written. re writing the clkpce bit with in this time-out period does neither extend th e time-out period, nor clear the clkpce bit. ? bits 3..0 ? clkps3..0: clock prescaler select bits 3 - 0 these bits define the division factor between the selected cl ock source and the internal system clock. these bits can be written run-time to vary the clock frequency to suit the applic ation requirements. as the divide r divides the master clock inpu t to the mcu, the speed of all synchronous peripherals is reduc ed when a division factor is used. the division factors are given in table 5-19 on page 58 . the ckdiv8 fuse determines the initial value of the clkps bits. if ckdiv8 is unprogrammed, the cl kps bits will be reset to ?0000?. if ckdiv8 is programmed, clkps bi ts are reset to ?0011?, giving a division factor of 8 at start up. this feature should be used if the selected clock source has a higher fr equency than the maximum frequency of the device at the present operating conditions. note that any value can be written to the clkps bits r egardless of the ckdiv8 fuse setting. the application software must ensure that a sufficient division factor is chosen if the selected clock source has a higher frequency than the maximum frequency of the device at the present operating conditions. the device is shipped with the ckdiv8 fuse programmed. bit 76543210 (0x66) cal7 cal6 cal5 cal4 cal3 cal2 cal1 cal0 osccal read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value device specific calibration value bit 76543210 (0x61) clkpce ? ? ? clkps3 clkps2 clkps1 clkps0 clkpr read/write r/w r r r r/w r/w r/w r/w initial value 0 0 0 0 see bit description
ata6614q [datasheet] 9240h?auto?10/14 58 5.9 power management and sleep modes sleep modes enable the application to shut down unused modules in the mcu, thereby saving power. the avr ? provides various sleep modes allowing the user to tailor the power consumption to the application?s requirements. when enabled, the brown-out detector (bod) actively monito rs the power supply voltage during the sleep periods. to further save power, it is possible to disable the bod in some sleep modes. see ?bod disable? on page 59 for more details. 5.9.1 sleep modes figure 5-10 on page 48 presents the different clock systems in the atmega328p , and their distribution. the figure is helpful in selecting an appropriate sleep mode. table 5-20 shows the different sleep modes, their wake up sources bod disable ability. notes: 1. only recommended with external crystal or resonator selected as clock source. 2. if timer/counter2 is running in asynchronous mode. 3. for int1 and int0, only level interrupt. table 5-19. clock prescaler select clkps3 clkps2 clkps1 clkps0 clock division factor 0 0 0 0 1 0 0 0 1 2 0 0 1 0 4 0 0 1 1 8 0 1 0 0 16 0 1 0 1 32 0 1 1 0 64 0 1 1 1 128 1 0 0 0 256 1 0 0 1 reserved 1 0 1 0 reserved 1 0 1 1 reserved 1 1 0 0 reserved 1 1 0 1 reserved 1 1 1 0 reserved 1 1 1 1 reserved table 5-20. active clock domains and wake-up sources in the different sleep modes. active clock domains oscillators wake-up sources software bod disable sleep mode clk cpu clk flash clk io clk adc clk asy main clock source enabled timer oscillator enabled int1, int0 and pin change twi address match timer2 spm/eeprom ready adc wdt other/o idle x x x x x (2) x x x x x x x adc noise reduction x x x x (2) x (3) x x (2) x x x power-down x (3) x x x power-save x x (2) x (3) x x x x standby (1) x x (3) x x x extended standby x (2) x x (2) x (3) x x x x
59 ata6614q [datasheet] 9240h?auto?10/14 to enter any of the six sleep modes, the se bit in smcr must be written to logic one and a sleep instruction must be executed. the sm2, sm1, and sm0 bits in the smcr register select which sle ep mode (idle, adc noise reduction, power-down, power-save, standby, or extended standby ) will be activated by the sleep instruction. see table 5-21 on page 62 for a summary. if an enabled interru pt occurs while the mcu is in a sleep mode, the mcu wakes up. the mc u is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execut ion from the instruction following sleep. the contents of the register file and sr am are unaltered when the device wakes up from sleep. if a reset occurs during sleep mode, the mcu wakes up and executes from the reset vector. 5.9.2 bod disable when the brown-out detector (bod ) is enabled by bodlevel fuses, table 5-117 on page 265 , the bod is actively monitoring the power supply voltage during a sleep period. to save power, it is possible to disable the bod by software for some of the sleep modes, see table 5-20 on page 58 . the sleep mode power consumption will then be at the same level as when bod is globally disabled by fuses. if bod is disabled in software, the bo d function is turned off immediately after entering the sleep mode. upon wake-up from sleep, bod is auto matically enabled again. this ensures safe operation in case the v cc level has dropped during the sleep period. when the bod has been disabled, the wake-up time from sleep mode will be approximately 60 s to ensure that the bod is working correctly before the mcu continues executing code. bod disable is controlled by bit 6, bods (bod sleep) in the control register mcucr, see section 5.9.11.2 ?mcucr ? mcu control register? on page 62 . writing this bit to one turns off the bod in rele vant sleep modes, while a zero in this bit keeps bod active. default setting keeps bo d active, i.e. bods set to zero. writing to the bods bit is controlled by a timed sequence and an enable bit, see section 5.9.11.2 ?mcucr ? mcu control register? on page 62 . 5.9.3 idle mode when the sm2..0 bits are written to 000, the sleep instruction makes the mcu enter idle mode, st opping the cpu but allowing the spi, usart, analog comparat or, adc, 2-wire serial interface, time r/counters, watchdog, and the interrupt system to continue operating. this sleep mode basically halts clk cpu and clk flash , while allowing the other clocks to run. idle mode enables the mcu to wake up from external triggered interrupts as well as internal ones like the timer overflow and usart transmit complete interrupts. if wa ke-up from the analog comparator interrupt is not required, the analog comparator can be powered down by setting the acd bit in the analog comp arator control and status regi ster ? acsr. this will reduce power consumption in idle mode. if the adc is enabled, a c onversion starts automatically when this mode is entered. 5.9.4 adc noise reduction mode when the sm2..0 bits are writ ten to 001, the sleep instruct ion makes the mcu enter adc no ise reduction mode, stopping the cpu but allowing the adc, the exte rnal interrupts, the 2-wire serial in terface address watch, timer/counter2 (1) , and the watchdog to continue operating (if enabled). this sleep mode basically halts clk i/o , clk cpu , and clk flash , while allowing the other clocks to run. this improves the noise environment for the adc, enabling higher resolution measurements. if the adc is enabled, a conversion starts automatically when th is mode is entered. apart from the adc conversion complete interrupt, only an external reset, a watchdog syst em reset, a watchdog interrupt, a brown-out re set, a 2-wire serial interface address match, a timer/counter2 interrupt, an spm/eeprom ready interrupt, an ex ternal level interrupt on int0 or int1 or a pin change interrupt can wake up the mcu from adc noise reduction mode. note: 1. timer/counter2 will only keep running in asynchronous mode, see section 5.17 ?8-bit timer/counter2 with pwm and asynchronous operation? on page 139 for details.
ata6614q [datasheet] 9240h?auto?10/14 60 5.9.5 power-down mode when the sm2..0 bits are written to 010, the sleep instruct ion makes the mcu enter power-down mode. in this mode, the external oscillator is stopped, while the external interrup ts, the 2-wire serial interface address watch, and the watchdog continue operating (if enabled). only an external reset, a watchdog system reset, a watchdog interrupt, a brown-out reset, a 2-wire serial interface address match, an external level interrupt on int0 or int1, or a pin change interrupt can wake up the mcu. this sleep mode basically halts all generated cl ocks, allowing operation of asynchronous modules only. note that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some time to wake up the mcu. refer to section 5.12 ?external interrupts? on page 77 for details. when waking up from power-down mode, there is a delay fr om the wake-up condition occurs until the wake-up becomes effective. this allows the clock to restart and become stable after having been stopped. the wake-up period is defined by the same cksel fuses that define the re set time-out period , as described in section 5.8.2 ?clock sources? on page 49 . 5.9.6 power-save mode when the sm2..0 bits are written to 011, the sleep instruction makes the m cu enter power-save m ode. this mode is identical to power-down, with one exception: if timer/counter2 is enabled, it will keep running during sleep. the device can wake up from either timer overflow or output compare event from timer/counter2 if the corresponding time r/counter2 interrupt enable bits are set in timsk2, and the global interrupt enable bit in sreg is set. if timer/counter2 is not running, power-down mo de is recommended instead of power-save mode. the timer/counter2 can be clocked both synchronously and asynchronously in power-save mode. if timer/counter2 is not using the asynchronous clock, the time r/counter oscillator is st opped during sleep. if timer/ counter2 is not using the synchronous clock, the clock source is stopped during sleep. no te that even if the synchronous clock is running in power- save, this clock is only av ailable for timer/counter2. 5.9.7 standby mode when the sm2..0 bits are 110 and an external crystal/resonato r clock option is selected, th e sleep instruction makes the mcu enter standby mode. this mode is identical to power-down with the exception that the o scillator is kept running. from standby mode, the device wakes up in six clock cycles. 5.9.8 extended standby mode when the sm2..0 bits are 111 and an external crystal/resonato r clock option is selected, th e sleep instruction makes the mcu enter extended standby mode. this mode is identical to power-save with the exception that the oscillator is kept running. from extended stan dby mode, the device wakes up in six clock cycles. 5.9.9 power reduction register the power reduction register (prr), see section 5.9.11.3 ?prr ? power reduction register? on page 63 , provides a method to stop the clock to individual peripherals to reduce po wer consumption. the current st ate of the peripheral is frozen and the i/o registers can not be read or written. resources used by the peripheral when stopping the clock will remain occupied, hence the peripheral should in most cases be disabl ed before stopping the clock. waking up a module, which is done by clearing the bit in prr, puts the mo dule in the same state as before shutdown. module shutdown can be used in idle mode and active mode to significantly reduce the overall power consumption. in all other sleep modes, the clock is already stopped. 5.9.10 minimizing power consumption there are several possibilities to consider when tr ying to minimize the power consumption in an avr ? controlled system. in general, sleep modes should be used as much as possible, a nd the sleep mode should be selected so that as few as possible of the device?s functions are op erating. all functions not needed should be disabled. in particular, the following modules may need special considerat ion when trying to achieve the lowest possible power consumption. 5.9.10.1 analog to digital converter if enabled, the adc will be enabled in all sleep modes. to save power, the adc should be disabled before entering any sleep mode. when the adc is turned off and on again, the next conversion will be an extended conversion. refer to section 5.23 ?analog-to-digital converter? on page 226 for details on adc operation.
61 ata6614q [datasheet] 9240h?auto?10/14 5.9.10.2 analog comparator when entering idle mode, the analog com parator should be disabled if not used. when entering adc noise reduction mode, the analog comparator should be disabled. in other sleep modes, the analog comp arator is automatically disabled. however, if the analog comparator is set up to us e the internal voltage reference as input, the analog comparator should be disabled in all sleep modes. otherwise, the internal voltage refer ence will be enabled, independent of sleep mode. refer to section 5.22 ?analog comparator? on page 223 for details on how to configure the analog comparator. 5.9.10.3 brown-out detector if the brown-out detector is not needed by the application, this module should be tur ned off. if the brown-out detector is enabled by the bodlevel fuses, it will be enabled in all sleep modes, and hence, always consume power. in the deeper sleep modes, this will contribute significantly to the total current consumption. refer to section 5.10.5 ?brown-out detection? on page 66 for details on how to configure the brown-out detector. 5.9.10.4 internal voltage reference the internal voltage reference will be enabled when needed by the brown-out detection, the ana log comparator or the adc. if these modules are disabled as described in the sections above, the internal volt age reference will be disabled and it will not be consuming power. when turned on again, the user must allow the reference to start up before the output is used. if the reference is kept on in sleep mode, the output can be used immediately. refer to section 5.10.7 ?internal voltage reference? on page 67 for details on the start-up time. 5.9.10.5 watchdog timer if the watchdog timer is not needed in t he application, the module should be turned off. if the watchdog timer is enabled, it will be enabled in all sleep modes and hence always consume power. in the deeper sleep modes, this will contribute significantly to the total cu rrent consumption. refer to section 5.10.8 ?watchdog timer? on page 68 for details on how to configure the watchdog timer. 5.9.10.6 port pins when entering a sleep mode, all port pins should be configured to use minimum power. the most important is then to ensure that no pins drive resistive loads. in sleep modes where both the i/o clock (clk i/o ) and the adc clock (clk adc ) are stopped, the input buffers of the device will be disabl ed. this ensures that no power is consum ed by the input logic when not needed. in some cases, the input logic is needed for detecting wake-up conditions, and it will then be enabled. refer to section 5.13.2.5 ?digital input enable and sleep modes? on page 86 for details on which pins are enabled. if the input buffer is enabled and the input signal is left floating or have an analog signal level close to v cc /2, the input buffer will use excessive power. for analog input pins, the digital input buffer should be disabled at all times. an analog signal level close to v cc /2 on an input pin can cause significant current even in active mode. digital input buffers can be disabled by writing to the digital input disable registers (didr1 and didr0). refer to section 5.22.3.3 ?didr1 ? digital i nput disable register 1? on page 225 and section 5.23.9.7 ?didr0 ? digital inpu t disable register 0? on page 241 for details. 5.9.10.7 on-chip debug system if the on-chip debug system is enabled by the dwen fuse and the chip enters sleep mode, the main clock source is enabled and hence always consumes power. in the deeper sleep modes, this will contribute significantly to the total current consumption.
ata6614q [datasheet] 9240h?auto?10/14 62 5.9.11 register description 5.9.11.1 smcr ? sleep mode control register the sleep mode control register contai ns control bits for power management. ? bits 7..4 res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bits 3..1 ? sm2..0: sleep mode select bits 2, 1, and 0 these bits select between the five available sleep modes as shown in table 5-21 . note: 1. standby mode is only recommended fo r use with external crystals or resonators. ? bit 0 ? se: sleep enable the se bit must be written to logic one to make the mcu enter the sleep mode when the sleep instruction is executed. to avoid the mcu entering the sleep mode unless it is the progra mmer?s purpose, it is recomm ended to write the sleep enable (se) bit to one just before the executio n of the sleep instruction and to cl ear it immediatel y after waking up. 5.9.11.2 mcucr ? mcu control register ? bit 6 ? bods: bod sleep the bods bit must be written to logic one in order to turn off bod during sleep, see table 5-20 on page 58 . writing to the bods bit is controlled by a timed sequence and an enable bit, bodse in mcucr. to disable bod in relevant sleep modes, both bods and bodse must first be set to one. then, to set the bods bit, bods must be set to one and bodse must be set to zero within four clock cycles. the bods bit is active three clock cycles after it is set. a sleep instruction must be executed wh ile bods is active in order t o turn off the bod for the actual sleep mode. the bods bit is automatically cleared after three clock cycles. ? bit 5 ? bodse: bod sleep enable bodse enables setting of bods control bit, as explained in bods bit description. bod disable is controlled by a timed sequence. bit 76543210 0x33 (0x53) ? ? ? ? sm2 sm1 sm0 se smcr read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 5-21. sleep mode select sm2 sm1 sm0 sleep mode 0 0 0 idle 0 0 1 adc noise reduction 0 1 0 power-down 0 1 1 power-save 1 0 0 reserved 1 0 1 reserved 1 1 0 standby (1) 1 1 1 external standby (1) bit 7 6 5 4 3 2 1 0 0x35 (0x55) ? bods bodse pud ? ? ivsel ivce mcucr read/write r r r r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0
63 ata6614q [datasheet] 9240h?auto?10/14 5.9.11.3 prr ? power reduction register ? bit 7 - prtwi: power reduction twi writing a logic one to this bit shuts down the twi by stopping the clock to the module. when waking up the twi again, the twi should be re initialized to ensure proper operation. ? bit 6 - prtim2: power reduction timer/counter2 writing a logic one to this bit shuts down the timer/co unter2 module in synchronous mode (as2 is 0). when the timer/counter2 is enabled, operation will continue like before the shutdown. ? bit 5 - prtim0: power reduction timer/counter0 writing a logic one to this bit shuts do wn the timer/counter0 module . when the timer/counter0 is enabled, operation will continue like before the shutdown. ? bit 4 - res: reserved bit this bit is reserved in atmega328p and will always read as zero. ? bit 3 - prtim1: power reduction timer/counter1 writing a logic one to this bit shuts do wn the timer/counter1 module . when the timer/counter1 is enabled, operation will continue like before the shutdown. ? bit 2 - prspi: power reduction serial peripheral interface if using debugwire on-chip debug system, this bit should not be written to one. writing a logic one to this bit shuts down the serial peripheral interface by stopping the clock to the module. when waking up the spi again, the spi should be re initialized to ensure proper operation. ? bit 1 - prusart0: power reduction usart0 writing a logic one to this bit shuts down the usart by stopping the clock to the module. when waking up the usart again, the usart should be re initialized to ensure proper operation. ? bit 0 - pradc: power reduction adc writing a logic one to this bit shuts down the adc. the a dc must be disabled before shut down. the analog comparator cannot use the adc input mux when the adc is shut down. 5.10 system control and reset 5.10.1 resetting the avr during reset, all i/o registers are set to their initial values, and the program starts execution from the reset vector. for th e atmega328p, the instruction placed at the reset vector must be an rjmp ? relative jump ? instruction to the reset handling routine. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the rese t vector is in the application section while the interrupt vecto rs are in the boot section. the circuit diagram in figure 5-14 on page 64 shows the reset logic. table 5-131 on page 280 defines the electrical parameters of the reset circuitry. the i/o ports of the avr ? are immediately reset to their initial state when a reset source goes active. this does not require any clock source to be running. bit 765432 1 0 (0x64) prtwi prtim2 prtim0 ? prtim1 prspi prusart0 pradc prr read/write r/w r/w r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
ata6614q [datasheet] 9240h?auto?10/14 64 after all reset sources have gone inactive, a delay counter is invo ked, stretching the internal reset. this allows the power to reach a stable level before normal operation starts. the time- out period of the delay counter is defined by the user through the sut and cksel fuses. the different se lections for t he delay period are presented in section 5.8.2 ?clock sources? on page 49 . 5.10.2 reset sources the atmega328p has four sources of reset: power-on reset. the mcu is reset when the supply voltage is below the power-on reset threshold (v pot ). external reset. the mcu is reset wh en a low level is present on the reset pin for longer than the minimum pulse length. watchdog system reset. the mcu is reset when the watc hdog timer period expires and the watchdog system reset mode is enabled. brown-out reset. the mcu is reset when the supply voltage v cc is below the brown-out reset threshold (v bot ) and the brown-out detector is enabled. figure 5-14. reset logic power-on reset circuit brown-out reset circuit mcu status register (mcusr) reset circuit pull-up resistor bodlevel[2..0] s q r data bus ck sut[1..0] cksel[3..0] rstdisbl counter reset internal reset timeout spike filter reset vcc delay counters watchdog timer watchdog oscillator clock generator porf borf wdrf extrf
65 ata6614q [datasheet] 9240h?auto?10/14 5.10.3 power-on reset a power-on reset (por) pulse is generated by an on-chip det ection circuit. the detection level is defined in section 5.28.5 ?system and reset characteristics? on page 280 . the por is activated whenever v cc is below the detection level. the por circuit can be used to trigger the start-up reset, as well as to detect a failure in supply voltage. a power-on reset (por) circuit ensures that the device is reset from power-on. reaching the power-on reset threshold voltage invokes the delay counter, which determine s how long the device is kept in reset after v cc rise. the reset signal is activated again, without any delay, when v cc decreases below the detection level. figure 5-15. mcu start-up, reset tied to v cc figure 5-16. . mcu start-up, reset extended externally note: 1. before rising, the supply has to be between v pormin and v pormax to ensure a reset table 5-22. power on reset specifications parameter symbol min typ max units power-on reset threshold voltage (rising) v pot 1.4 v power-on reset threshold voltage (falling) (1) 1.0 1.3 1.6 v vcc max. start voltage to ensure internal power-on reset signal v pormax 0.4 v vcc min. start voltage to ensure internal power-on reset signal v pormin -0.1 v vcc rise rate to ensure power-on reset v ccrr 0.01 v/ms v pot v rst v cc reset internal reset time-out t tout v cc reset internal reset time-out v pot v rst t tout
ata6614q [datasheet] 9240h?auto?10/14 66 5.10.4 external reset an external reset is generated by a low level on the reset pin. reset pulses longer than the minimum pulse width (see section 5.28.5 ?system and reset characteristics? on page 280 ) will generate a reset, even if the clock is not running. shorter pulses are not guaranteed to generate a reset. when the applied signal reaches the reset threshold voltage ? v rst ? on its positive edge, the delay counter star ts the mcu after the time-out period ? t tout ? has expired. the external reset can be disabled by the rstdisbl fuse, see table 5-117 on page 265 . figure 5-17. external reset during operation 5.10.5 brown-out detection atmega328p has an on-chip brown-out detection (bod) circuit for monitoring the v cc level during operation by comparing it to a fixed trigger level. the trigger level for the bod can be selected by the bodlevel fuses. the tri gger level has a hysteresis to ensure spike free brown-out detection. the hy steresis on the detection level should be interpreted as v bot+ = v bot + v hyst /2 and v bot- = v bot - v hyst /2.when the bod is enabled, and v cc decreases to a value below the trigger level (v bot- in figure 5-18 on page 66 ), the brown-out reset is i mmediately activated. when v cc increases above the trigger level (v bot+ in figure 5-18 on page 66 ), the delay counter starts the mcu after the time-out period t tout has expired. the bod circuit will only detect a drop in v cc if the voltage stays below the trigger level for longer than t bod given in section 5.28.5 ?system and reset characteristics? on page 280 . figure 5-18. brown-out reset during operation t tout reset internal reset time-out v rst v cc v bot- v bot+ t tout v cc reset internal reset time-out
67 ata6614q [datasheet] 9240h?auto?10/14 5.10.6 watchdog system reset when the watchdog times out, it will generate a short reset pulse of one ck cycle duration. on the falling edge of this pulse, the delay timer starts counting the time-out period t tout . refer to section 5.10.8 ?watchdog timer? on page 68 for details on operation of the watchdog timer. figure 5-19. watchdog system reset during operation 5.10.7 internal voltage reference atmega328p features an internal bandgap reference. this refere nce is used for brown-out detection, and it can be used as an input to the analog comparator or the adc. 5.10.7.1 voltage reference enab le signals and start-up time the voltage reference has a start-up time that may influence the way it should be used. the start-up time is given in section 5.28.5 ?system and reset characteristics? on page 280 . to save power, the reference is not always turned on. the reference is on during the following situations: 1. when the bod is enabled (by programming the bodlevel [2:0] fuses). 2. when the bandgap reference is connected to the analog comparator (by setting the acbg bit in acsr). 3. when the adc is enabled. thus, when the bod is not enabled, af ter setting the acbg bit or enabling the adc, the user must always allow the reference to start up before the output fr om the analog comparator or adc is used. to reduce power consumption in power- down mode, the user can avoid the three conditions above to en sure that the reference is turned off before entering power- down mode. 1 ck cycle v cc reset internal reset reset time-out wdt time-out t tout
ata6614q [datasheet] 9240h?auto?10/14 68 5.10.8 watchdog timer 5.10.8.1 features clocked from separate on-chip oscillator 3 operating modes interrupt system reset interrupt and system reset selectable time-out period from 16ms to 8s possible hardware fuse watchdog always on (wdton) for fail-safe mode 5.10.8.2 overview atmega328p has an enhanced watchdog timer (wdt). the wdt is a timer counting cycles of a separate on-chip 128khz oscillator. the wdt gives an interrupt or a system reset w hen the counter reaches a given time-out value. in normal operation mode, it is required that the syst em uses the wdr - watchdog timer reset - instruction to restar t the counter before the time-out value is reached. if the system doesn't restart the counter, an interrupt or system reset will be issued. figure 5-20. watchdog timer in interrupt mode, the wdt gives an interrupt when the timer expires. this interrupt can be used to wake the device from sleep-modes, and also as a general system timer. one exampl e is to limit the maximum time allowed for certain operations, giving an interrupt when the operation has run longer than expected. in system reset mode, the wdt gives a reset when the timer expires. this is typically used to prevent system hang- up in case of runaway code. the third mode, interrupt and system reset mode, combines the other two modes by first giving an interrupt and th en switch to syste m reset mode. this mode will for instance allow a safe shutdown by savi ng critical parameters before a system reset. the watchdog always on (w dton) fuse, if programmed, will force the watch dog timer to system rese t mode. with the fuse programmed the system reset mode bit (wde) and interrupt mode bit (wdie) are locke d to 1 and 0 respectively. to further ensure program security, alterations to the watchdog set-up must follow timed sequences. the sequence for clearing wde and changing time-out configuration is as follows: 1. in the same operation, write a logic one to the wa tchdog change enable bit (wdce) and wde. a logic one must be written to wde regardless of t he previous value of the wde bit. 2. within the next four clock cycles, write the wde and watchdog prescaler bits (wdp) as desired, but with the wdce bit cleared. this must be done in one operation. osc/64k osc/16k osc/2k osc/4k osc/8k osc/32k osc/128k osc/256k osc/512k osc/1024k watchdog prescaler wdp0 wde watchdog reset wdif wdie wdp1 wdp2 wdp3 mcu reset interrupt 128khz oscillator
69 ata6614q [datasheet] 9240h?auto?10/14 the following code example shows one assembly and one c function for turning off the watchdog timer. the example assumes that interrupts are controlled (e.g. by disabling in terrupts globally) so that no interrupts will occur during the execution of these functions. notes: 1. see section 5.5 ?about code examples? on page 32 . 2. if the watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the watchdog timer will stay enabled. if the code is not set up to handle the watchdog, this might lead to an eternal loop of time-out resets. to av oid this situation, the application software should always clear the watchdog system reset flag (wdrf) and the wde control bit in the initializ ation routine, even if the watchdog is not in use. assembly code example (1) wdt_off: ; turn off global interrupt cli ; reset watchdog timer wdr ; clear wdrf in mcusr in r16, mcusr andi r16, (0xff & (0< ata6614q [datasheet] 9240h?auto?10/14 70 the following code example shows one assembly and one c functi on for changing the time-out value of the watchdog timer. notes: 1. see section 5.5 ?about code examples? on page 32 . 2. the watchdog timer should be reset before any change of the wdp bits, since a change in the wdp bits can result in a time-out when switch ing to a shorter time-out period. assembly code example (1) wdt_prescaler_change: ; turn off global interrupt cli ; reset watchdog timer wdr ; start timed sequence lds r16, wdtcsr ori r16, (1< 71 ata6614q [datasheet] 9240h?auto?10/14 5.10.9 register description 5.10.9.1 mcusr ? mcu status register the mcu status register provides informati on on which reset source caused an mcu reset. ? bit 7..4: res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 3 ? wdrf: watchdog system reset flag this bit is set if a watchdog system reset occurs. the bit is re set by a power-on reset, or by writing a logic zero to the flag . ? bit 2 ? borf: brown-out reset flag this bit is set if a brown-out reset occu rs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 1 ? extrf: external reset flag this bit is set if an external reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 0 ? porf: power-on reset flag this bit is set if a power-on reset occurs. the bit is reset only by writing a logic zero to the flag. to make use of the reset flags to identify a reset condition, the user should read and then reset the mcusr as early as possible in the program. if the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags. 5.10.9.2 wdtcsr ? watchdog timer control register ? bit 7 - wdif: watc hdog interrupt flag this bit is set when a time-out occurs in the watchdog timer and the watchdog timer is configured for interrupt. wdif is cleared by hardware when executing the corre sponding interrupt handling vector. alternat ively, wdif is cleared by writing a logic one to the flag. when the i-bit in sreg and wdie are set, the watchdog time-o ut interrupt is executed. ? bit 6 - wdie: watchdog interrupt enable when this bit is written to one and the i- bit in the status register is set, the watchdog interrupt is enabled. if wde is clear ed in combination with this setting, the watchdog timer is in interr upt mode, and the corresponding interrupt is executed if time-out in the watchdog timer occurs. if wde is set, the watchdog timer is in interrupt and system reset mode. the first time-out in the watchdog timer will set wdif. executing the corresponding interrupt vector will clear wdie and wdif automatically by ha rdware (the watchdog goes to system reset mode). this is useful for keepi ng the watchdog timer security while usi ng the interrupt. to stay in interrupt and system reset mode, wdie must be set after each interrupt. this should however not be done within the interrupt service routine itself, as this might compromise the safety-function of the watchdog system reset mode. if the interrupt is not executed before the next time-o ut, a system reset will be applied. bit 76543210 0x35 (0x55) ? ? ? ? wdrf borf extrf porf mcusr read/write rrrrr/wr/wr/wr/w initial value 0 0 0 0 see bit description bit 76543210 (0x60) wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 wdtcsr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 x 0 0 0
ata6614q [datasheet] 9240h?auto?10/14 72 note: 1. wdton fuse set to ?0? means programmed and ?1? means unprogrammed. ? bit 4 - wdce: watchdog change enable this bit is used in timed sequences for changing wde and pre scaler bits. to clear the wde bit, and/or change the prescaler bits, wdce must be set. once written to one, hardware will cl ear wdce after four clock cycles. ? bit 3 - wde: watchdog system reset enable wde is overridden by wdrf in mcusr. this means that wde is always set when wdrf is set. to clear wde, wdrf must be cleared first. this feature ensu res multiple resets during conditions caus ing failure, and a safe start-up after the failure. ? bit 5, 2..0 - wdp3..0: watchdog timer prescaler 3, 2, 1 and 0 the wdp3..0 bits determine the watchdog timer prescaling wh en the watchdog timer is running. the different prescaling values and their corresponding time-out periods are shown in table 5-24 . table 5-23. watchdog timer configuration wdton (1) wde wdie mode action on time-out 1 0 0 stopped none 1 0 1 interrupt mode interrupt 1 1 0 system reset mode reset 1 1 1 interrupt and system reset mode interrupt, then go to system reset mode 0 x x system reset mode reset table 5-24. watchdog timer prescale select wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 16ms 0 0 0 1 4k (4096) cycles 32ms 0 0 1 0 8k (8192) cycles 64ms 0 0 1 1 16k (16384) cycles 0.125s 0 1 0 0 32k (32768) cycles 0.25s 0 1 0 1 64k (65536) cycles 0.5s 0 1 1 0 128k (131072) cycles 1.0s 0 1 1 1 256k (262144) cycles 2.0s 1 0 0 0 512k (524288) cycles 4.0s 1 0 0 1 1024k (1048576) cycles 8.0s 1 0 1 0 reserved 1 0 1 1 1 1 0 0 1 1 0 1 1 1 1 0 1 1 1 1
73 ata6614q [datasheet] 9240h?auto?10/14 5.11 interrupts this section describes the specifics of the interrupt handling as performed in atmega328p. for a general explanation of the avr ? interrupt handling, refer to section 5.6.7 ?reset and interrupt handling? on page 39 . each interrupt vector occupies two instruction words in atmega328p. in atmega328p, the reset vector is affected by the bootrst fuse, and the interrupt vector start address is affected by the ivsel bit in mcucr. 5.11.1 interrupt vectors in atmega328p table 5-25. reset and interrupt vectors in atmega328p vector no. program address source interrupt definition 1 0x0000 reset external pin, power-on reset, brown-out reset and watchdog system reset 2 0x002 int0 external interrupt request 0 3 0x0004 int1 external interrupt request 1 4 0x0006 pcint0 pin change interrupt request 0 5 0x0008 pcint1 pin change interrupt request 1 6 0x000a pcint2 pin change interrupt request 2 7 0x000c wdt watchdog time-out interrupt 8 0x000e timer2 compa timer/counter2 compare match a 9 0x0010 timer2 compb timer/counter2 compare match b 10 0x0012 timer2 ovf timer/counter2 overflow 11 0x0014 timer1 capt timer/counter1 capture event 12 0x0016 timer1 compa timer/counter1 compare match a 13 0x0018 timer1 compb timer/counter1 compare match b 14 0x001a timer1 ovf timer/counter1 overflow 15 0x001c timer0 compa timer/counter0 compare match a 16 0x001e timer0 compb timer/counter0 compare match b 17 0x0020 timer0 ovf timer/counter0 overflow 18 0x0022 spi, stc spi serial transfer complete 19 0x0024 usart, rx usart rx complete 20 0x0026 usart, udre usart, data register empty 21 0x0028 usart, tx usart, tx complete 22 0x002a adc adc conversion complete 23 0x002c ee ready eeprom ready 24 0x002e analog comp analog comparator 25 0x0030 twi 2-wire serial interface 26 0x0032 spm ready store program memory ready
ata6614q [datasheet] 9240h?auto?10/14 74 table 5-26 on page 74 shows reset and interrupt vectors placement fo r the various combinations of bootrst and ivsel settings. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the rese t vector is in the application section while the interrupt vecto rs are in the boot section or vice versa. note: 1. for the bootrst fuse ?1? means unprogrammed while ?0? means programmed. the most typical and general program setup for the re set and interrupt vector addresses in atmega328p is: address labels code comments 0x0000 jmp reset ; reset handler 0x0002 jmp ext_int0 ; irq0 handler 0x0004 jmp ext_int1 ; irq1 handler 0x0006 jmp pcint0 ; pcint0 handler 0x0008 jmp pcint1 ; pcint1 handler 0x000a jmp pcint2 ; pcint2 handler 0x000c jmp wdt ; watchdog timer handler 0x000e jmp tim2_compa ; timer2 compare a handler 0x0010 jmp tim2_compb ; timer2 compare b handler 0x0012 jmp tim2_ovf ; timer2 overflow handler 0x0014 jmp tim1_capt ; timer1 capture handler 0x0016 jmp tim1_compa ; timer1 compare a handler 0x0018 jmp tim1_compb ; timer1 compare b handler 0x001a jmp tim1_ovf ; timer1 overflow handler 0x001c jmp tim0_compa ; timer0 compare a handler 0x001e jmp tim0_compb ; timer0 compare b handler 0x0020 jmp tim0_ovf ; timer0 overflow handler 0x0022 jmp spi_stc ; spi transfer complete handler 0x0024 jmp usart_rxc ; usart, rx complete handler 0x0026 jmp usart_udre ; usart, udr empty handler 0x0028 jmp usart_txc ; usart, tx complete handler 0x002a jmp adc ; adc conversion complete handler 0x002c jmp ee_rdy ; eeprom ready handler 0x002e jmp ana_comp ; analog comparator handler 0x0030 jmp twi ; 2-wire serial interface handler 0x0032 jmp spm_rdy ; store program memory ready handler ; 0x0033 reset: ldi r16, high(ramend) ; main program start 0x0034 out sph,r16 ; set stack pointer to top of ram 0x0035 ldi r16, low(ramend) 0x0036 out spl,r16 0x0037 sei ; enable interrupts 0x0038 xxx ... ... ... ... table 5-26. reset and interrupt vectors placement in atmega328p (1) bootrst ivsel reset address interrupt vectors start address 1 0 0x000 0x002 1 1 0x000 boot reset address + 0x0002 0 0 boot reset address 0x002 0 1 boot reset address boot reset address + 0x0002
75 ata6614q [datasheet] 9240h?auto?10/14 when the bootrst fuse is unprogrammed, the boot section size set to 2kbytes and the ivsel bit in the mcucr register is set before any interrupts are enabled, the most typical and general program setup for the reset and interrupt vector addresses in atmega328p is: address labels code comments 0x0000 reset: ldi r16,high(ramend) ; main program start 0x0001 out sph,r16 ; set stack pointer to top of ram 0x0002 ldi r16,low(ramend) 0x0003 out spl,r16 0x0004 sei ; enable interrupts 0x0005 xxx ; .org 0x3c02 0x3c02 jmp ext_int0 ; irq0 handler 0x3c04 jmp ext_int1 ; irq1 handler ... ... ... ; 0x3c32 jmp spm_rdy ; store program memory ready handler when the bootrst fuse is programmed and the boot section si ze set to 2kbytes, the most typical and general program setup for the reset and interrupt vector addresses in atmega328p is: address labels code comments .org 0x0002 0x0002 jmp ext_int0 ; irq0 handler 0x0004 jmp ext_int1 ; irq1 handler ... ... ... ; 0x0032 jmp spm_rdy ; store program memory ready handler ; .org 0x3c00 0x3c00 reset: ldi r16,high(ramend) ; main program start 0x3c01 out sph,r16 ; set stack pointer to top of ram 0x3c02 ldi r16,low(ramend) 0x3c03 out spl,r16 0x3c04 sei ; enable interrupts 0x3c05 xxx when the bootrst fuse is programmed, the boot section size set to 2kbytes and the ivsel bit in the mcucr register is set before any interrupts are enabled, the most typical and general program setup for the reset and interrupt vector addresses in atmega328p is: address labels code comments ; .org 0x3c00 0x3c00 jmp reset ; reset handler 0x3c02 jmp ext_int0 ; irq0 handler 0x3c04 jmp ext_int1 ; irq1 handler ... ... ... ; 0x3c32 jmp spm_rdy ; store program memory ready handler ; 0x3c33 reset: ldi r16,high(ramend) ; main program start 0x3c34 out sph,r16 ; set stack pointer to top of ram 0x3c35 ldi r16,low(ramend) 0x3c36 out spl,r16 0x3c37 sei ; enable interrupts 0x3c38 xxx
ata6614q [datasheet] 9240h?auto?10/14 76 5.11.2 register description 5.11.2.1 moving interrupts betwee n application and boot space the mcu control register controls the pl acement of the interrupt vector table. 5.11.2.2 mcucr ? mcu control register ? bit 1 ? ivsel: interrupt vector select when the ivsel bit is cleared (z ero), the interrupt vectors are placed at the start of the flas h memory. when this bit is set (one), the interrupt vectors are moved to t he beginning of the boot loader section of t he flash. the actual address of the star t of the boot flash section is determi ned by the bootsz fuses. refer to section 5.26 ?boot loader support ? read-while- write self-programming? on page 250 for details. to avoid unintentional changes of interrupt vector tables, a special write procedure must be followed to change the ivsel bit: a. write the interrupt vector change enable (ivce) bit to one. b. within four cycles, write th e desired value to ivsel whil e writing a zero to ivce. interrupts will automat ically be disabled while this sequence is executed. interrupts ar e disabled in the cycle ivce is set, an d they remain disabled until after the instru ction following th e write to ivsel. if ivsel is not written, interrupts remain disab led for four cycles. the i-bit in th e status register is unaffect ed by the automatic disabling. note: if interrupt vectors are placed in the boot loader se ction and boot lock bit blb02 is programmed, interrupts are disabled while executing from the application section. if interrupt vectors are placed in the application section and boot lock bit blb12 is programed, interrupts are disa bled while executing from the boot loader section. refer to section 5.26 ?boot loader support ? read-while-write self-programming? on page 250 for details on boot lock bits. this bit is not available in atmega328p. ? bit 0 ? ivce: interrupt vector change enable the ivce bit must be written to logic one to enable change of t he ivsel bit. ivce is cleared by hardware four cycles after it is written or when ivsel is written. setting the ivce bit will disable interrupts, as explained in the ivsel description above. see code example below. this bit is not available in atmega328p. bit 76543210 0x35 (0x55) ? bods bodse pud ? ? ivsel ivce mcucr read/write r r r r/w r r r/w r/w initial value00000000 assembly code example move_interrupts: ; enable change of interrupt vectors ldi r16, (1< 77 ata6614q [datasheet] 9240h?auto?10/14 5.12 external interrupts the external interrupts are triggered by the int0 and int1 pins or any of the pcint23..0 pins . observe that, if enabled, the interrupts will trigger even if the int0 and int1 or pcint23..0 pi ns are configured as outputs. th is feature provides a way of generating a software interrupt. the pin change interrupt pci2 w ill trigger if any enabled pcint23..16 pin toggles. the pin change interrupt pci1 will trigger if any enabled pcint14..8 pi n toggles. the pin change interr upt pci0 will trigger if any enabled pcint7..0 pin toggles. the pcmsk2, pcmsk1 and pcmsk0 registers control which pins contribute to the pin change interrupts. pin change interrupts on pcint23..0 are detect ed asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the int0 and int1 interrupts can be triggered by a falling or ri sing edge or a low level. this is set up as indicated in the specification for the external interrupt control register a ? eicra. when the int0 or int1 interrupts are enabled and are configured as level triggered, the interrupts will trigger as long as the pin is held lo w. note that recognition of falling or rising edge interrupts on int0 or int1 requires the presence of an i/o clock, described in section 5.8.1 ?clock systems and their distribution? on page 48 . low level interrupt on int0 and int1 is detected asyn chronously. this implies that this interrupt can be used for waking the part also from sleep modes other than idle mode. the i/o clock is halted in all sleep modes except idle mode. note that if a level triggered interrupt is used for wake-up from power-down, the required level must be held long enough for the mcu to complete the wake-up to trigger the level interrupt . if the level disappears before t he end of the start-up time, th e mcu will still wake up, but no interrupt will be generated. the start-up time is defined by the sut and cksel fuses as described in section 5.8 ?system clock and clock options? on page 48 . 5.12.1 pin change interrupt timing an example of timing of a pin change interrupt is shown in figure 5-21 . figure 5-21. timing of pin change interrupts clk pin_lat pin_sync pcint(0) pcint_in(0) pcint_sync pcint_set/flag pcif pin_lat pin_sync pcint_sync clk 0 x clk pcint_set/flag pcint(0) in pcmsk(x) pcint(0) pin pcif pcint_in(0) le dq dq dq dq
ata6614q [datasheet] 9240h?auto?10/14 78 5.12.2 register description 5.12.2.1 eicra ? external in terrupt control register a the external interrupt control register a contai ns control bits for interrupt sense control. ? bit 7..4 ? res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 3, 2 ? isc11, isc10: interrupt sense control 1 bit 1 and bit 0 the external interrupt 1 is activated by the external pin int1 if the sreg i-flag and the corre sponding interrupt mask are set. the level and edges on the external int1 pin that activate the interrupt are defined in table 5-27 . the value on the int1 pin is sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last l onger than one clock period will generate an interrupt. shorter pulses are no t guaranteed to generate an interrupt. if low level interrupt is selected, the low level must be held until the completion of the current ly executing instruction to generate an interrupt. ? bit 1, 0 ? isc01, isc00: interrupt sense control 0 bit 1 and bit 0 the external interrupt 0 is activated by the external pin int0 if the sreg i-flag and the corre sponding interrupt mask are set. the level and edges on the external int0 pin that activate the interrupt are defined in table 5-28 . the value on the int0 pin is sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last l onger than one clock period will generate an interrupt. shorter pulses are no t guaranteed to generate an interrupt. if low level interrupt is selected, the low level must be held until the completion of the current ly executing instruction to generate an interrupt. bit 76543210 (0x69) ? ? ? ? isc11 isc10 isc01 isc00 eicra read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 5-27. interrupt 1 sense control isc11 isc10 description 0 0 the low level of int1 generates an interrupt request. 0 1 any logical change on int1 generates an interrupt request. 1 0 the falling edge of int1 generates an interrupt request. 1 1 the rising edge of int1 generates an interrupt request. table 5-28. interrupt 0 sense control isc01 isc00 description 0 0 the low level of int0 generates an interrupt request. 0 1 any logical change on int0 generates an interrupt request. 1 0 the falling edge of int0 generates an interrupt request. 1 1 the rising edge of int0 generates an interrupt request.
79 ata6614q [datasheet] 9240h?auto?10/14 5.12.2.2 eimsk ? external interrupt mask register ? bit 7..2 ? res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 1 ? int1: external interrupt request 1 enable when the int1 bit is set (one) and the i-bit in the status regi ster (sreg) is set (one), the ex ternal pin interrupt is enabled. the interrupt sense control1 bits 1/0 (isc11 and isc10) in t he external interrupt control r egister a (eicra) define whether the external interrupt is activated on rising and/or falling edge of the int1 pin or level sensed. activity on the pin will cau se an interrupt request even if int1 is configured as an output. th e corresponding interrupt of external interrupt request 1 is executed from the int1 interrupt vector. ? bit 0 ? int0: external interrupt request 0 enable when the int0 bit is set (one) and the i-bit in the status regi ster (sreg) is set (one), the ex ternal pin interrupt is enabled. the interrupt sense control0 bits 1/0 (isc01 and isc00) in t he external interrupt control r egister a (eicra) define whether the external interrupt is activated on rising and/or falling edge of the int0 pin or level sensed. activity on the pin will cau se an interrupt request even if int0 is configured as an output. th e corresponding interrupt of external interrupt request 0 is executed from the int0 interrupt vector. 5.12.2.3 eifr ? external interrupt flag register ? bit 7..2 ? res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 1 ? intf1: external interrupt flag 1 when an edge or logic change on the int1 pin triggers an inte rrupt request, intf1 becomes set (one). if the i-bit in sreg and the int1 bit in eimsk are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. this flag is always c leared when int1 is configured as a level interrupt. ? bit 0 ? intf0: external interrupt flag 0 when an edge or logic change on the int0 pin triggers an inte rrupt request, intf0 becomes set (one). if the i-bit in sreg and the int0 bit in eimsk are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. this flag is always c leared when int0 is configured as a level interrupt. bit 76543210 0x1d (0x3d) ? ? ????int1int0eimsk read/write r r rrrrr/wr/w initial value00000000 bit 76543210 0x1c (0x3c) ? ? ????intf1intf0eifr read/write r r rrrrr/wr/w initial value00000000
ata6614q [datasheet] 9240h?auto?10/14 80 5.12.2.4 pcicr ? pin change interrupt control register ? bit 7..3 - res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 2 - pcie2: pin change interrupt enable 2 when the pcie2 bit is set (one) and the i-bit in the status regi ster (sreg) is set (one), pin change interrupt 2 is enabled. an y change on any enabled pcint23..16 pin will cause an interrupt. the corresponding interrupt of pin change interrupt request is executed from the pci2 interrupt vector. pcint23..16 pins are enabled individually by the pcmsk2 register. ? bit 1 - pcie1: pin change interrupt enable 1 when the pcie1 bit is set (one) and the i-bit in the status regi ster (sreg) is set (one), pin change interrupt 1 is enabled. an y change on any enabled pcint14..8 pin will cause an interrupt. the corresponding interrupt of pin change interrupt request is executed from the pci1 interrupt vector. pcint14..8 pins are enabled individually by the pcmsk1 register. ? bit 0 - pcie0: pin change interrupt enable 0 when the pcie0 bit is set (one) and the i-bit in the status regi ster (sreg) is set (one), pin change interrupt 0 is enabled. an y change on any enabled pcint7..0 pin will cause an interrupt. t he corresponding interrupt of pin change interrupt request is executed from the pci0 interrupt vector. pcint7..0 pi ns are enabled individually by the pcmsk0 register. 5.12.2.5 pcifr ? pin change interrupt flag register ? bit 7..3 - res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 2 - pcif2: pin change interrupt flag 2 when a logic change on any pcint23..16 pin triggers an interru pt request, pcif2 becomes set (one). if the i-bit in sreg and the pcie2 bit in pcicr are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. ? bit 1 - pcif1: pin change interrupt flag 1 when a logic change on any pcint14..8 pin triggers an interrupt request, pcif1 becomes set (one ). if the i-bit in sreg and the pcie1 bit in pcicr are set (one), the mcu will jump to t he corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the fl ag can be cleared by writing a logical one to it. ? bit 0 - pcif0: pin change interrupt flag 0 when a logic change on any pcint7..0 pin triggers an inte rrupt request, pcif0 becomes set (one). if the i-bit in sreg and the pcie0 bit in pcicr are set (one), the mcu will jump to t he corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the fl ag can be cleared by writing a logical one to it. bit 76543210 (0x68) ? ? ? ? ? pcie2 pcie1 pcie0 pcicr read/write r r r r r r/w r/w r/w initial value00000000 bit 76543210 0x1b (0x3b) ? ? ? ? ? pcif2 pcif1 pcif0 pcifr read/write r r r r r r/w r/w r/w initial value00000000
81 ata6614q [datasheet] 9240h?auto?10/14 5.12.2.6 pcmsk2 ? pin change mask register 2 ? bit 7..0 ? pcint23..16: pin change enable mask 23..16 each pcint23..16-bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pcint23..16 is set and the pcie2 bit in pcicr is set, pin change interrupt is enable d on the corresponding i/o pin. if pcint23..16 is cleared, pin change interrupt on the corresponding i/o pin is disabled. 5.12.2.7 pcmsk1 ? pin change mask register 1 ? bit 7 ? res: reserved bit this bit is an unused bit in the atmega328p, and will always read as zero. ? bit 6..0 ? pcint14..8: pin change enable mask 14..8 each pcint14..8-bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pcint14..8 is set and the pcie1 bit in pcicr is set, pin change interrupt is enabled on the corresponding i/o pin. if pcint14..8 is cleared, pin change interrupt on the corresponding i/o pin is disabled. 5.12.2.8 pcmsk0 ? pin change mask register 0 ? bit 7..0 ? pcint7..0: pi n change enable mask 7..0 each pcint7..0 bit selects whether pin change interrupt is enabl ed on the corresponding i/o pin. if pcint7..0 is set and the pcie0 bit in pcicr is set, pin change interrupt is enabled on the corresponding i/o pin. if pcint7..0 is cleared, pin change interrupt on the corresponding i/o pin is disabled. bit 76543210 (0x6d) pcint23 pcint22 pcint21 pcint20 pcint19 pcint18 pcint17 pcint16 pcmsk2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x6c) ? pcint14 pcint13 pcint12 pcint11 pcint10 pcint9 pcint8 pcmsk1 read/write r r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x6b) pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 pcmsk0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
ata6614q [datasheet] 9240h?auto?10/14 82 5.13 i/o-ports 5.13.1 overview all avr ? ports have true read-modify- write functionality when used as general digita l i/o ports. this means that the direction of one port pin can be changed without uni ntentionally changing the direction of any other pin with the sbi and cbi instructions. the same applies when changing drive value (if configured as output) or enabling/ disabling of pull-up resistors (if configured as input). each output buffer has symmetrical dr ive characteristics with both high sink and source capability. the pin driver is strong enough to drive le d displays directly. all port pins have individually selectable pull-up resistors wi th a supply-voltage invariant resistance. all i/o pins have protection diodes to both v cc and ground as indicated in figure 5-22 . refer to section 5.28 ?electrical characteristics? on page 278 for a complete list of parameters. figure 5-22. i/o pin equivalent schematic all registers and bit references in this section are written in general form. a lower case ?x? represents the numbering letter for the port, and a lower case ?n? represents the bit number. howeve r, when using the register or bit defines in a program, the precise form must be used. for example, portb3 for bit no. 3 in port b, here documented generally as portxn. the physical i/o registers and bi t locations ar e listed in section 5.13.4 ?register description? on page 96 . three i/o memory address locations are allocated for each po rt, one each for the data register ? portx, data direction register ? ddrx, and the port input pins ? pi nx. the port input pins i/o location is read only, while the data register and the data direction register are read/write. howeve r, writing a logic one to a bit in the pinx register, will result in a toggle in the corresponding bit in the data register. in addition, the pull-up disable ? pud bit in mcucr disables the pull-up function for a ll pins in all ports when set. using the i/o port as general digital i/o is described in section 5.13.2 ?ports as general digital i/o? on page 83 . most port pins are multiplexed with alternate functi ons for the peripheral features on the device. how each alternate function interferes with the port pin is described in section 5.13.3 ?alternate po rt functions? on page 87 . refer to the individual module sections for a full description of the alternate functions. note that e nabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital i/o. c pin r pu pxn logic see figure general digital i/o for details
83 ata6614q [datasheet] 9240h?auto?10/14 5.13.2 ports as general digital i/o the ports are bi-directional i/o port s with optional internal pull-ups. figure 5-23 shows a functional description of one i/o- port pin, here generically called pxn. figure 5-23. general digital i/o (1) note: 1. wrx, wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. 5.13.2.1 configuring the pin each port pin consists of three register bi ts: ddxn, portxn, and pinxn. as shown in section 5.13.4 ?register description? on page 96 , the ddxn bits are accessed at the ddrx i/o address, the portxn bits at the portx i/o address, and the pinxn bits at the pinx i/o address. the ddxn bit in the ddrx register selects the direction of this pin. if ddxn is written logic one, pxn is configured as an output pin. if ddxn is written logic zero , pxn is configured as an input pin. if portxn is written logic one when the pin is configured as an input pin, the pull-up resistor is activated. to switch the pul l- up resistor off, portxn has to be written logic zero or the pin has to be configured as an output pin. the port pins are tri- stated when reset condition becomes active, even if no clocks are running. if portxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). if portxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero). d 0 1 q wrx rrx wpx pnx clr reset synchronizer data bus portxn q q l d q q d q pinxn reset rpx wdx: write ddrx wrx: wpx: rpx: rrx: read portx register read portx pin write pinx register rdx: write portx read ddrx pud: pullup disable clk i/o : sleep: i/o clock sleep control rdx clk i/o pud wdx sleep d q clr ddxn q
ata6614q [datasheet] 9240h?auto?10/14 84 5.13.2.2 toggling the pin writing a logic one to pinxn toggles the value of portxn, independent on the value of ddrxn. note that the sbi instruction can be used to toggle one single bit in a port. 5.13.2.3 switching between input and output when switching between tri-state ({ddxn, portxn} = 0b00) and output high ({ddxn, portxn} = 0b11), an intermediate state with either pull-up enabled {ddxn, portxn} = 0b01) or output low ({ddxn, portxn} = 0 b10) must occur. normally, the pull-up enabled state is fully acceptable , as a high-impedance environment will not notice the difference between a strong high driver and a pull-up. if this is not the case, the pud bit in the mcucr register can be set to disable all pull-ups in all ports. switching between input with pull-up and out put low generates the same problem. th e user must use ei ther the tri-state ({ddxn, portxn} = 0b00) or the out put high state ({ddxn, portxn} = 0b11) as an intermediate step. table 5-29 summarizes the control signals for the pin value. 5.13.2.4 reading the pin value independent of the setting of data direct ion bit ddxn, the port pin can be read thro ugh the pinxn register bit. as shown in figure 5-23 on page 83 , the pinxn register bit and the preceding latch co nstitute a synchronizer. this is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. figure 5-24 shows a timing diagram of the synchronization when reading an externally applied pin value. the maximum and minimum propagation delays are denoted t pd,max and t pd,min respectively. figure 5-24. synchronization when reading an externally applied pin value consider the clock period starting shortl y after the first fallin g edge of the system cl ock. the latch is closed when the clock is low, and goes transparent when the clock is high, as indicate d by the shaded region of the ?sync latch? signal. the signal value is latched when the system clock goes low. it is clocked into the pinxn regist er at the succeeding positive clock edge. as indicated by the two arrows tpd,max and tpd,min, a sing le signal transition on the pin will be delayed between ? and 1? system clock period depending upon the time of assertion. when reading back a software assigned pin value, a n op instruction must be inserted as indicated in figure 5-25 . the out instruction sets the ?sync latch? signal at the positive edge of the clock. in this case, the delay tpd through the synchronizer is 1 system clock period. table 5-29. port pin configurations ddxn portxn pud (in mcucr) i/o pull-up comment 0 0 x input no tri-state (hi-z) 0 1 0 input yes pxn will source current if ext. pulled low. 0 1 1 input no tri-state (hi-z) 1 0 x output no output low (sink) 1 1 x output no output high (source) system clk instructions sync latch pinxn r17 xxx xxx 0x00 0xff in r17, pinx t pd, max t pd, min
85 ata6614q [datasheet] 9240h?auto?10/14 figure 5-25. synchronization when reading a software assigned pin value the following code example shows how to set port b pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. the resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read ba ck the value recently assigned to some of the pins. note: 1. for the assembly program, two temporary registers are used to minimize the time from pull-ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly se t, defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers. assembly code example (1) ... ; define pull-ups and set outputs high ; define directions for port pins ldi r16,(1< ata6614q [datasheet] 9240h?auto?10/14 86 5.13.2.5 digital input en able and sleep modes as shown in figure 5-23 on page 83 , the digital input signal can be clamped to ground at the input of the schmitt trigger. the signal denoted sleep in the figure, is set by the m cu sleep controller in power-down mode, power-save mode, and standby mode to avoid high power consumption if some input signal s are left floating, or have an analog signal level close to v cc /2. sleep is overridden for port pins enabled as external interrupt pins. if the external interrupt request is not enabled, sleep is active also for these pins. sleep is also overridden by various other alternate functions as described in section 5.13.3 ?alternate port functions? on page 87 . if a logic high level (?one?) is present on an asynchronous extern al interrupt pin configured as ?interrupt on rising edge, falling edge, or any logic change on pi n? while the external interrupt is not enabled, the corresponding external interrupt flag will be set when resuming from the above mentioned sle ep mode, as the clamping in these sleep mode produces the requested logic change. 5.13.2.6 unconnected pins if some pins are unused, it is recommend ed to ensure that these pins have a defined level. even though most of the digital inputs are disabled in the deep sleep modes as described ab ove, floating inputs should be avoided to reduce current consumption in all other modes where the digital in puts are enabled (reset, active mode and idle mode). the simplest method to ensure a defined level of an unused pin, is to enable the inte rnal pull-up. in this case, the pull-up wi ll be disabled during reset. if low power consumption during reset is important, it is re commended to use an external pull-up or pull-down. connecting unused pins directly to v cc or gnd is not recommended, since this may cause excessive currents if the pin is accidentally configured as an output.
87 ata6614q [datasheet] 9240h?auto?10/14 5.13.3 alternate port functions most port pins have alternate functions in addition to being general digital i/os. figure 5-26 shows how the port pin control signals from the simplified figure 5-23 on page 83 can be overridden by alternate functions. the overriding signals may not be present in all port pins, but the figure serves as a generic description applicable to all port pins in the avr ? microcontroller family. figure 5-26. alternate port functions (1) note: 1. wrx, wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. all other signals are unique for each pin. d 0 1 q wrx rrx wpx ptoexn pxn clr reset synchronizer data bus portxn q 0 1 q l d set clr clr q q d q pinxn 0 1 reset rpx pxn pull-up override enable pxn pull-up override value pud: pull-up disable puoexn: pxn port value override value pvovxn: pxn port value override enable pvoexn: pxn data direction override enable pxn data direction override value ddoexn: ddovxn: sleep control sleep: pxn, port toggle override enable ptoexn: pxn digital input enable override value dieovxn: pxn digital input enable override enable dieoexn: i/o clock rdx: rpx: write pinx wrx: analog input/output pin n on portx digital input pin n on portx rrx: read portx register wpx: write portx aioxn: dixn: read portx pin wdx: read ddrx write ddrx puovxn: rdx clk i/o dixn aioxn clk: i/o dieovxn dieoexn pvoexn ddoexn pvovxn 0 1 puoexn puovxn 0 1 ddovxn sleep pud wdx d q clr ddxn q
ata6614q [datasheet] 9240h?auto?10/14 88 table 5-30 summarizes the function of the overriding signals. the pin and port indexes from figure 5-26 on page 87 are not shown in the succeeding tables. the overriding signals are generat ed internally in the modules having the alternate function. the following subsections shortly describe the alternate functi ons for each port, and relate the overriding signals to the alternate function. refer to the alternat e function description for further details. table 5-30. generic description of overri ding signals for alternate functions signal name full name description puoe pull-up override enable if this signal is set, the pull-up enable is controlled by the puov signal. if this signal is cleared, the pull-up is enabled when {ddxn, portxn, pud} = 0b010. puov pull-up override value if puoe is set, the pull-up is enabl ed/disabled when puov is set/cleared, regardless of the setting of the dd xn, portxn, and pud register bits. ddoe data direction override enable if this signal is set, the output driver enable is controlled by the ddov signal. if this signal is cleared, t he output driver is enabled by the ddxn register bit. ddov data direction override value if ddoe is set, the output driver is enabled/disabled when ddov is set/cleared, regardless of the se tting of the ddxn register bit. pvoe port value override enable if this signal is set and the output driver is enabled, the port value is controlled by the pvov signal. if pvoe is cleared, and the output driver is enabled, the port value is controlled by the portxn register bit. pvov port value override value if pvoe is set, the port value is set to pvov, regardless of the setting of the portxn register bit. ptoe port toggle override enable if ptoe is set, the portxn register bit is inverted. dieoe digital input enable override enable if this bit is set, the digital input enable is controlled by the dieov signal. if this signal is cleared, the digital input enable is determined by mcu state (normal mode, sleep mode). dieov digital input enable override value if dieoe is set, the digital input is enabled/disabled when dieov is set/cleared, regardless of the m cu state (normal mode, sleep mode). di digital input this is the digital input to alternate functions. in the figure, the signal is connected to the output of the schmit t trigger but before the synchronizer. unless the digital input is used as a clock source, the module with the alternate function will use its own synchronizer. aio analog input/output this is the analog input/output to/fro m alternate functions. the signal is connected directly to the pad, and can be used bi-directionally.
89 ata6614q [datasheet] 9240h?auto?10/14 5.13.3.1 alternate functions of port b the port b pins with alternate functions are shown in table 5-31 the alternate pin configuration is as follows: ? xtal2/tosc2/pcint7 ? port b, bit 7 xtal2: chip clock oscillator pin 2. used as clock pin for crystal oscillator or low-frequency crystal o scillator. when used as a clock pin, the pin can not be used as an i/o pin. tosc2: timer oscillator pin 2. used only if internal calibrated rc oscillator is selected as chip cl ock source, and the asynchronous timer is enabled by the correct setting in assr. when the as2 bit in assr is set (one) and the exclk bit is cleared (zero) to enable asynchronous clocking of timer/counter 2 using the crystal oscillator, pin pb7 is disconnected from the port, and becomes the inverting output of the oscillator amplifier. in this mode, a crystal oscillator is connected to this pin, and the pin cannot be used as an i/o pin. pcint7: pin change interrupt source 7. the pb7 pin can serve as an external interrupt source. if pb7 is used as a clock pin, ddb7, portb7 and pinb7 will all read 0. ? xtal1/tosc1/pcint6 ? port b, bit 6 xtal1: chip clock oscillator pin 1. used for all chip clock so urces except internal calibrated rc oscillator. when used as a clock pin, the pin can not be used as an i/o pin. tosc1: timer oscillator pin 1. used only if internal calibrated rc oscillator is selected as chip cl ock source, and the asynchronous timer is enabled by the correct setting in assr. when the as2 bit in assr is set (one) to enable asynchronous clocking of timer/counter2, pin pb6 is disconnec ted from the port, and becomes the input of the inverting oscillator amplifier. in this mode, a cryst al oscillator is connected to this pin, and the pin can not be used as an i/o pin. pcint6: pin change interrupt source 6. the pb6 pin can serve as an external interrupt source. if pb6 is used as a clock pin, ddb6, portb6 and pinb6 will all read 0. table 5-31. port b pins alternate functions port pin alternate functions pb7 xtal2 ( chip clock oscillator pin 2 ) tosc2 ( timer oscillator pin 2 ) pcint7 (pin change interrupt 7) pb6 xtal1 ( chip clock oscillator pin 1 or external clock input ) tosc1 ( timer oscillator pin 1 ) pcint6 (pin change interrupt 6) pb5 sck (spi bus master clock input) pcint5 (pin change interrupt 5) pb4 miso (spi bus master input/slave output) pcint4 (pin change interrupt 4) pb3 mosi (spi bus master output/slave input) oc2a (timer/counter2 output compare match a output) pcint3 (pin change interrupt 3) pb2 ss (spi bus master slave select) oc1b (timer/counter1 output compare match b output) pcint2 (pin change interrupt 2) pb1 oc1a (timer/counter1 output compare match a output) pcint1 (pin change interrupt 1) pb0 icp1 (timer/counter1 input capture input) clko (divided syst em clock output) pcint0 (pin change interrupt 0)
ata6614q [datasheet] 9240h?auto?10/14 90 ? sck/pcint5 ? port b, bit 5 sck: master clock output, slave clock input pin for spi channel. wh en the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb5. when the spi is enabled as a master, the data direct ion of this pin is controlled by ddb5. when the pin is forced by the spi to be an inpu t, the pull-up can still be co ntrolled by the portb5 bit. pcint5: pin change interrupt source 5. the pb5 pin can serve as an external interrupt source. ? miso/pcint4 ? port b, bit 4 miso: master data input, slave data output pin for spi channel. when the spi is enabled as a master, this pin is configured as an input regardless of the setting of ddb 4. when the spi is enabled as a slave, th e data direction of this pin is controlled by ddb4. when the pin is forced by the spi to be an inpu t, the pull-up can still be co ntrolled by the portb4 bit. pcint4: pin change interrupt source 4. the pb4 pin can serve as an external interrupt source. ? mosi/oc2/pcint3 ? port b, bit 3 mosi: spi master data output, slave data input for spi channel. wh en the spi is enabled as a slav e, this pin is configured as an input regardless of the setting of ddb3. when the spi is enabled as a master, the data direction of this pin is controlled by ddb3. when the pi n is forced by the spi to be an input, the pull- up can still be controlled by the portb3 bit. oc2, output compare match output: the pb3 pin can serve as an external output for the timer/counter2 compare match. the pb3 pin has to be configured as an output (ddb3 set (one)) to serve this function. the oc2 pin is also the output pin for the pwm mode timer function. pcint3: pin change interrupt source 3. the pb3 pin can serve as an external interrupt source. ?ss /oc1b/pcint2 ? port b, bit 2 ss : slave select input. when the spi is enabled as a slave, this pin is configured as an input regardless of the setting of ddb2. as a slave, the spi is activated when this pin is dr iven low. when the spi is enabled as a master, the data direction of this pin is controlled by ddb2. when the pin is forced by th e spi to be an input, the pull-up can still be controlled by the portb2 bit. oc1b, output compare match output: the pb2 pin can serve as an external output for the timer/counter1 compare match b. the pb2 pin has to be configured as an output (ddb2 set (one)) to serve this function. the oc1b pin is also the output pin for the pwm mode timer function. pcint2: pin change interrupt source 2. the pb2 pin can serve as an external interrupt source. ? oc1a/pcint1 ? port b, bit 1 oc1a, output compare match output: the pb1 pin can serve as an external output for the timer/counter1 compare match a. the pb1 pin has to be configured as an output (ddb1 set (one)) to serve this function. the oc1a pin is also the output pin for the pwm mode timer function. pcint1: pin change interrupt source 1. the pb1 pin can serve as an external interrupt source. ? icp1/clko/pcint0 ? port b, bit 0 icp1, input capture pin: the pb0 pin can act as an input capture pin for timer/counter1. clko, divided system clock: the divided system clock can be out put on the pb0 pin. the divi ded system clock will be output if the ckout fuse is programmed, rega rdless of the portb0 and ddb0 settings. it will also be output during reset. pcint0: pin change interrupt source 0. the pb0 pin can serve as an external interrupt source. table 5-32 and table 5-33 on page 91 relate the alternate functions of port b to the overriding signals shown in figure 5-26 on page 87 . spi mstr input and spi slave output constitute the miso signal, while mosi is divided into spi mstr output and spi slave input.
91 ata6614q [datasheet] 9240h?auto?10/14 notes: 1. intrc means that one of the internal rc oscillato rs are selected (by the cksel fuses), extck means that external clock is select ed (by the cksel fuses) table 5-32. overriding signals for alternate functions in pb7..pb4 signal name pb7/xtal2/ tosc2/pcint7 (1) pb6/xtal1/ tosc1/pcint6 (1) pb5/sck/ pcint5 pb4/miso/ pcint4 puoe intrc extck + as2 intrc + as2 spe mstr spe mstr puov 0 0 portb5 pud portb4 pud ddoe intrc extck + as2 intrc + as2 spe mstr spe mstr ddov 0 0 0 0 pvoe 0 0 spe mstr spe mstr pvov 0 0 sck output spi slave output dieoe intrc extck + as2 + pcint7 pcie0 intrc + as2 + pcint6 pcie0 pcint5 pcie0 pcint4 pcie0 dieov (intrc + extck) as2 intrc as2 1 1 di pcint7 input pcint6 input pcint5 input sck input pcint4 input spi mstr input aio oscillator output oscillator/clock input ? ? table 5-33. overriding signals for alternate functions in pb3..pb0 signal name pb3/mosi/ oc2/pcint3 pb2/ss / oc1b/pcint2 pb1/oc1a/ pcint1 pb0/icp1/ pcint0 puoe spe mstr spe mstr 0 0 puov portb3 pud portb2 pud 0 0 ddoe spe mstr spe mstr 0 0 ddov 0 0 0 0 pvoe spe mstr + oc2a enable oc1b enable oc1a enable 0 pvov spi mstr output + oc2a oc1b oc1a 0 dieoe pcint3 pcie0 pcint2 pcie0 pcint1 pcie0 pcint0 pcie0 dieov 1 1 1 1 di pcint3 input spi slave input pcint2 input spi ss pcint1 input pcint0 input icp1 input aio ? ? ? ?
ata6614q [datasheet] 9240h?auto?10/14 92 5.13.3.2 alternate functions of port c the port c pins with alternate functions are shown in table 5-34 . the alternate pin configuration is as follows: ? reset /pcint14 ? port c, bit 6 reset , reset pin: when the rstdisbl fuse is programmed, this pin functions as an input pin, and the part will have to rely on power-on reset and brown-out reset as its reset sour ces. when the rstdisbl fuse is unprogrammed, the reset circuitry is connected to the pin, and the pin can not be used as an input pin. if pc6 is used as a reset pin, d dc6, portc6 and pinc6 will all read 0. pcint14: pin change interrupt source 14. the pc6 pin can serve as an external interrupt source. ? scl/adc5/pcint13 ? port c, bit 5 scl, 2-wire serial interface clock: when the twen bit in twcr is set (one) to enable the 2-wire serial interface, pin pc5 is disconnected from the port and becomes the serial clock i/o pin fo r the 2-wire serial interface. in this mode, there is a spike filter on the pin to suppress spikes shorte r than 50 ns on the input signal, and the pi n is driven by an open drain driver with slew-rate limitation. pc5 can also be used as adc input channel 5. no te that adc input channel 5 uses digital power. pcint13: pin change interrupt source 13. the pc5 pin can serve as an external interrupt source. ? sda/adc4/pcint12 ? port c, bit 4 sda, 2-wire serial interface data: when the twen bit in twcr is set (one) to enable the 2-wire serial interface, pin pc4 is disconnected from the port and becomes the serial data i/o pin fo r the 2-wire serial interface. in this mode, there is a spike filter on the pin to suppress spikes shorter than 50ns on the i nput signal, and the pin is driven by an open drain driver with slew-rate limitation. pc4 can also be used as adc input channel 4. no te that adc input channel 4 uses digital power. pcint12: pin change interrupt source 12. the pc4 pin can serve as an external interrupt source. ? adc3/pcint11 ? port c, bit 3 pc3 can also be used as adc input channel 3. no te that adc input channel 3 uses analog power. pcint11: pin change interrupt source 11. the pc3 pin can serve as an external interrupt source. table 5-34. port c pins alternate functions port pin alternate function pc6 reset (reset pin) pcint14 (pin change interrupt 14) pc5 adc5 (adc input channel 5) scl (2-wire serial bus clock line) pcint13 (pin change interrupt 13) pc4 adc4 (adc input channel 4) sda (2-wire serial bus data input/output line) pcint12 (pin change interrupt 12) pc3 adc3 (adc input channel 3) pcint11 (pin change interrupt 11) pc2 adc2 (adc input channel 2) pcint10 (pin change interrupt 10) pc1 adc1 (adc input channel 1) pcint9 (pin change interrupt 9) pc0 adc0 (adc input channel 0) pcint8 (pin change interrupt 8)
93 ata6614q [datasheet] 9240h?auto?10/14 ? adc2/pcint10 ? port c, bit 2 pc2 can also be used as adc input channel 2. no te that adc input channel 2 uses analog power. pcint10: pin change interrupt source 10. the pc2 pin can serve as an external interrupt source. ? adc1/pcint9 ? port c, bit 1 pc1 can also be used as adc input channel 1. no te that adc input channel 1 uses analog power. pcint9: pin change interrupt source 9. the pc1 pin can serve as an external interrupt source. ? adc0/pcint8 ? port c, bit 0 pc0 can also be used as adc input channel 0. no te that adc input channel 0 uses analog power. pcint8: pin change interrupt source 8. the pc0 pin can serve as an external interrupt source. table 5-35 and table 5-36 relate the alternate functions of port c to the overriding signals shown in figure 5-26 on page 87 . note: 1. when enabled, the 2-wire serial interface enables slew -rate controls on the output pi ns pc4 and pc5. this is not shown in the figure. in addition, spike filters are connected between the aio outputs shown in the port fig- ure and the digital logic of the twi module. table 5-35. overriding signals for alternate functions in pc6..pc4 (1) signal name pc6/reset /pcint14 pc5/scl/adc5/pcint13 pc4/sda/adc4/pcint12 puoe rstdisbl twen twen puov 1 portc5 pud portc4 pud ddoe rstdisbl twen twen ddov 0 scl_out sda_out pvoe 0 twen twen pvov 0 0 0 dieoe rstdisbl + pcint14 pcie1 pcint13 pcie1 + adc5d pcint12 pcie1 + adc4d dieov rstdisbl pcint13 pcie1 pcint12 pcie1 di pcint14 input pcint13 input pcint12 input aio reset input adc5 input / scl input adc4 input / sda input table 5-36. overriding signals for alternate functions in pc3..pc0 signal name pc3/adc3/ pcint11 pc2/adc2/ pcint10 pc1/adc1/ pcint9 pc0/adc0/ pcint8 puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe 0 0 0 0 pvov 0 0 0 0 dieoe pcint11 pcie1 + adc3d pcint10 pcie1 + adc2d pcint9 pcie1 + adc1d pcint8 pcie1 + adc0d dieov pcint11 pcie1 pcint10 pcie1 pcint9 pcie1 pcint8 pcie1 di pcint11 input pcint10 input pcint9 input pcint8 input aio adc3 input adc2 input adc1 input adc0 input
ata6614q [datasheet] 9240h?auto?10/14 94 5.13.3.3 alternate functions of port d the port d pins with alternate functions are shown in table 5-37 . the alternate pin configuration is as follows: ? ain1/oc2b/pcint23 ? port d, bit 7 ain1, analog comparator negative input. configure the port pin as input with the internal pull-up switched off to avoid the digital port function from interfering with the function of the analog comparator. pcint23: pin change interrupt source 23. the pd7 pin can serve as an external interrupt source. ? ain0/oc0a/pcint22 ? port d, bit 6 ain0, analog comparator positiv e input. configure the port pin as input with th e internal pull-up switched off to avoid the digital port function from interfering with the function of the analog comparator. oc0a, output compare match output: the pd6 pin can serve as an external output for the timer/counter0 compare match a. the pd6 pin has to be configured as an output (ddd6 set (one)) to serve this function. the oc0a pin is also the output pin for the pwm mode timer function. pcint22: pin change interrupt source 22. the pd6 pin can serve as an external interrupt source. ? t1/oc0b/pcint21 ? port d, bit 5 t1, timer/counter1 counter source. oc0b, output compare match output: the pd5 pin can serve as an external output for the timer/counter0 compare match b. the pd5 pin has to be configured as an output (ddd5 set (one)) to serve this function. the oc0b pin is also the output pin for the pwm mode timer function. pcint21: pin change interrupt source 21. the pd5 pin can serve as an external interrupt source. table 5-37. port d pins alternate functions port pin alternate function pd7 ain1 (analog comparator negative input) pcint23 (pin change interrupt 23) pd6 ain0 (analog comparator positive input) oc0a (timer/counter0 output compare match a output) pcint22 (pin change interrupt 22) pd5 t1 (timer/counter 1 external counter input) oc0b (timer/counter0 output compare match b output) pcint21 (pin change interrupt 21) pd4 xck (usart external clock input/output) t0 (timer/counter 0 external counter input) pcint20 (pin change interrupt 20) pd3 int1 (external interrupt 1 input) oc2b (timer/counter2 output compare match b output) pcint19 (pin change interrupt 19) pd2 int0 (external interrupt 0 input) pcint18 (pin change interrupt 18) pd1 txd (usart output pin) pcint17 (pin change interrupt 17) pd0 rxd (usart input pin) pcint16 (pin change interrupt 16)
95 ata6614q [datasheet] 9240h?auto?10/14 ? xck/t0/pcint20 ? port d, bit 4 xck, usart ex ternal clock. t0, timer/counter0 counter source. pcint20: pin change interrupt source 20. the pd4 pin can serve as an external interrupt source. ? int1/oc2b/pcint19 ? port d, bit 3 int1, external interrupt source 1: the pd3 pin can serve as an external interrupt source. oc2b, output compare match output: the pd3 pin can serve as an external output for the timer/counter0 compare match b. the pd3 pin has to be configured as an output (ddd3 set (one)) to serve this function. the oc2b pin is also the output pin for the pwm mode timer function. pcint19: pin change interrupt source 19. the pd3 pin can serve as an external interrupt source. ? int0/pcint18 ? port d, bit 2 int0, external interrupt source 0: the pd2 pin can serve as an external interrupt source. pcint18: pin change interrupt source 18. the pd2 pin can serve as an external interrupt source. ? txd/pcint17 ? port d, bit 1 txd, transmit data (data output pin for the usart). when the usart transmitter is enabled, this pin is configured as an output regardless of the value of ddd1. pcint17: pin change interrupt source 17. the pd1 pin can serve as an external interrupt source. ? rxd/pcint16 ? port d, bit 0 rxd, receive data (data input pin for t he usart). when the usart receiver is e nabled this pin is configured as an input regardless of the value of ddd0. when t he usart forces this pin to be an input, the pull-up can still be controlled by the portd0 bit. pcint16: pin change interrupt source 16. the pd0 pin can serve as an external interrupt source. table 5-38 and table 5-39 relate the alternate functions of port d to the overriding signals shown in figure 5-26 on page 87 . table 5-38. overriding signals fo r alternate functions pd7..pd4 signal name pd7/ain1 /pcint23 pd6/ain0/ oc0a/pcint22 pd5/t1/oc0b/ pcint21 pd4/xck/ t0/pcint20 puoe 0 0 0 0 puo 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe 0 oc0a enable oc0b enable umsel pvov 0 oc0a oc0b xck output dieoe pcint23 pcie2 pcint22 pcie2 pcint21 pcie2 pcint20 pcie2 dieov 1 1 1 1 di pcint23 input pcint22 input pcint21 input t1 input pcint20 input xck input t0 input aio ain1 input ain0 input ? ?
ata6614q [datasheet] 9240h?auto?10/14 96 5.13.4 register description 5.13.4.1 mcucr ? mcu control register ? bit 4 ? pud: pull-up disable when this bit is written to one, the pull-ups in the i/o po rts are disabled even if the ddxn and portxn registers are configured to enable the pull-ups ({ddxn, portxn} = 0b01). see section 5.13.2.1 ?configur ing the pin? on page 83 for more details about this feature. 5.13.4.2 portb ? the port b data register 5.13.4.3 ddrb ? the port b data direction register table 5-39. overriding signals for alternate functions in pd3..pd0 signal name pd3/oc2b/int1/ pcint19 pd2/int0/ pcint18 pd1/txd/ pcint17 pd0/rxd/ pcint16 puoe 0 0 txen rxen puo 0 0 0 portd0 pud ddoe 0 0 txen rxen ddov 0 0 1 0 pvoe oc2b enable 0 txen 0 pvov oc2b 0 txd 0 dieoe int1 enable + pcint19 pcie2 int0 enable + pcint18 pcie1 pcint17 pcie2 pcint16 pcie2 dieov 1 1 1 1 di pcint19 input int1 input pcint18 input int0 input pcint17 input pcint16 input rxd aio ? ? ? ? bit 7 6 5 4 3 2 1 0 0x35 (0x55) ? bods bodse pud ? ? ivsel ivce mcucr read/write r r r r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x05 (0x25) portb7 portb6 portb5 port b4 portb3 portb2 portb1 portb0 portb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x04 (0x24) ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 ddrb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
97 ata6614q [datasheet] 9240h?auto?10/14 5.13.4.4 pinb ? the port b input pins address 5.13.4.5 portc ? the port c data register 5.13.4.6 ddrc ? the port c data direction register 5.13.4.7 pinc ? the port c input pins address 5.13.4.8 portd ? the port d data register 5.13.4.9 ddrd ? the port d data direction register 5.13.4.10 pind ? the port d input pins address bit 76543210 0x03 (0x23) pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 pinb read/write r r r r r r r r initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 0x08 (0x28) ? portc6 portc5 portc4 portc3 portc2 portc1 portc0 portc read/write r r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x07 (0x27) ? ddc6 ddc5 ddc4 ddc3 ddc2 ddc1 ddc0 ddrc read/write r r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x06 (0x26) ? pinc6 pinc5 pinc4 pinc3 pinc2 pinc1 pinc0 pinc read/write r r r r r r r r initial value 0 n/a n/a n/a n/a n/a n/a n/a bit 76543210 0x0b (0x2b) portd7 portd6 portd5 port d4 portd3 portd2 portd1 portd0 portd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x0a (0x2a) ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 ddrd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x09 (0x29) pind7 pind6 pind5 pind4 pind3 pind2 pind1 pind0 pind read/write r r r r r r r r initial value n/a n/a n/a n/a n/a n/a n/a n/a
ata6614q [datasheet] 9240h?auto?10/14 98 5.14 8-bit timer/counter0 with pwm 5.14.1 features two independent output compare units double buffered out put compare registers clear timer on compare match (auto reload) glitch free, phase correct pulse width modulator (pwm) variable pwm period frequency generator three independent interrupt sources (tov0, ocf0a, and ocf0b) 5.14.2 overview timer/counter0 is a general purpose 8-bit timer/counter mo dule, with two independent outpu t compare units, and with pwm support. it allows accurate program execution timing (event management) and wave generation. a simplified block diagram of the 8-bit timer/counter is shown in figure 5-27 . the device-specific i/o register and bit locations are listed in section 5.14.9 ?register description? on page 107 . the prtim0 bit in section 5.9.10 ?minimizing power consumption? on page 60 must be written to zero to enable timer/counter0 module. figure 5-27. 8-bit timer/counter block diagram tcntn timer/counter count clear direction ocrna ocrnb tccrna tccrnb = top bottom ocna (int. req.) waveform generation fixed top value data bus = = = 0 ocna ocnb (int. req.) waveform generation ocnb control logic clk tn tovn (int. req.) edge detector (from prescaler) clock select tn
99 ata6614q [datasheet] 9240h?auto?10/14 5.14.2.1 definitions many register and bit references in this section are written in general form. a lower case ?n? replaces the timer/counter number, in this case 0. a lower case ?x? replaces the output compare unit, in this case compare unit a or compare unit b. however, when using the register or bit defines in a progr am, the precise form must be used, i.e., tcnt0 for accessing timer/counter0 counter value and so on. the definitions in table 5-40 are also used extensively throughout the document. 5.14.2.2 registers the timer/counter (tcnt0) and output compare registers (o cr0a and ocr0b) are 8-bit registers. interrupt request (abbreviated to int.req. in the figure) signals are all visible in the timer interrupt flag register (tifr0). all interrupts ar e individually masked with the timer inte rrupt mask register (timsk0). tifr0 and timsk0 are not shown in the figure. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the t0 pin. th e clock select logic block controls which clock source and edge the timer/ counter uses to increment (o r decrement) its value. the timer/counter is inactive when no clock source is selected. the out put from the clock select logic is referred to as the timer clock (clk t0 ). the double buffered output compare registers (ocr0a and ocr0b) are compared with the timer/counter value at all times. the result of the compare can be used by the waveform generator to generate a pwm or variable frequency output on the output compare pins (oc0a and oc0b). see section 5.15.7.3 ?using the out put compare unit? on page 122 for details. the compare match event will also set the compare flag (o cf0a or ocf0b) which can be used to generate an output compare interrupt request. 5.14.3 timer/counter clock sources the timer/counter can be clocked by an internal or an extern al clock source. the clock sour ce is selected by the clock select logic which is controlled by the clock select (cs02:0) bi ts located in the timer/counter control register (tccr0b). for details on clock source s and prescaler, see section 5.16 ?timer/counter0 and timer/ counter1 prescalers? on page 137 . 5.14.4 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 5-28 shows a block diagram of the counter and its surroundings. figure 5-28. counter unit block diagram table 5-40. definitions case definition bottom the counter reaches the bottom when it becomes 0x00. max the counter reaches its maximum when it becomes 0xff (decimal 255). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr0a register. the assignment is dependent on the mode of operation. top bottom tovn (int. req.) data bus control logic tcntn clk tn count clear direction edge detector (from prescaler) clock select tn
ata6614q [datasheet] 9240h?auto?10/14 100 signal description (internal signals): count increment or decrement tcnt0 by 1. direction select between increment and decrement. clear clear tcnt0 (set all bits to zero). clk t n timer/counter clock, referred to as clk t0 in the following. top signalize that tcnt0 has reached maximum value. bottom signalize that tcnt0 has reached minimum value (zero). depending of the mode of operation used, the counter is clea red, incremented, or decreme nted at each timer clock (clk t0 ). clk t0 can be generated from an external or internal clock source , selected by the clock select bits (cs02:0). when no clock source is selected (cs02:0 = 0) the time r is stopped. however, the tcnt0 value can be accessed by the cpu, regardless of whether clk t0 is present or not. a cpu write overrides (has pr iority over) all counter clear or count operations. the counting sequence is determined by the setting of the wgm01 and wgm00 bits located in the timer/counter control register (tccr0a) and the wgm02 bit located in the timer/counter control register b (tccr0b). there are close connections between how the counter behaves (counts) and ho w waveforms are generated on the output compare outputs oc0a and oc0b. for more details about advanced counting sequences and waveform generation, see section 5.14.7 ?modes of operation? on page 102 . the timer/counter overflow flag (tov0) is set according to t he mode of operation selected by the wgm02:0 bits. tov0 can be used for generating a cpu interrupt. 5.14.5 output compare unit the 8-bit comparator continuously compares tcnt0 with the output compare register s (ocr0a and ocr0b). whenever tcnt0 equals ocr0a or ocr0b, the comparator signals a ma tch. a match will set the outpu t compare flag (ocf0a or ocf0b) at the next timer clo ck cycle. if the corresponding interrupt is enabled , the output compare fl ag generates an output compare interrupt. the output compare flag is automatically cleared when the interrupt is executed. alternatively, the flag can be cleared by software by writing a logical one to its i/o bit location. the waveform generator uses the match signal to generate an output according to operating mode set by the wg m02:0 bits and compare output mode (com0x1:0) bits. the max and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation ( section 5.14.7 ?modes of operation? on page 102 ). figure 5-29 shows a block diagram of the output compare unit. figure 5-29. output comp are unit, block diagram ocfnx (int. req.) = (8-bit comparator) ocrnx waveform generator tcntn ocnx top bottom focn wgmn[1:0] comnx[1:0] data bus
101 ata6614q [datasheet] 9240h?auto?10/14 the ocr0x registers are double buffered when using any of the pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the doubl e buffering is disabled. the double buffering synchronizes the update of the ocr0x compare registers to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr0x register access may seem co mplex, but this is not case. when th e double buffering is enabled, the cpu has access to the ocr0x buffer register, and if double buffer ing is disabled the cpu will access the ocr0x directly. 5.14.5.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (foc0x) bit. forcing compare match will not set the ocf0x flag or reload/clear the timer, but the oc0x pin will be updated as if a real compare match had occurred (the co m0x1:0 bits settings define w hether the oc0x pin is set, cleared or toggled). 5.14.5.2 compare match blocking by tcnt0 write all cpu write operations to the tcnt0 register will block any compare match th at occur in the next timer clock cycle, even when the timer is stopped. this feature allows ocr0x to be initialized to the same value as tcnt0 without triggering an interrupt when the timer/counter clock is enabled. 5.14.5.3 using the ou tput compare unit since writing tcnt0 in any mode of ope ration will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt0 when using the output compare unit, independently of whether the timer/counter is running or not. if the value written to tcnt0 equals the ocr0x value, the compare match will be missed, resulting in incorrect waveform generation. similarly, do not write the tcnt0 valu e equal to bottom when the counter is downcounting. the setup of the oc0x should be performed bef ore setting the data direction register for the port pin to output. the easiest way of setting the oc0x value is to use the force output co mpare (foc0x) strobe bits in normal mode. the oc0x registers keep their values even when changing between waveform generation modes. be aware that the com0x1:0 bits are not double buffered together with the compar e value. changing the com0x1:0 bits will take effect immediately. 5.14.6 compare match output unit the compare output mode (com0x1:0) bits have two functi ons. the waveform generator uses the com0x1:0 bits for defining the output compare (oc0x) state at the next compare match. also, the com0x1:0 bits control the oc0x pin output source. figure 5-30 on page 102 shows a simplified schematic of the logic af fected by the com0x1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bo ld. only the parts of the general i/o port control registers (dd r and port) that are affected by the com0x1:0 bits are shown. when referring to the oc0x state, th e reference is for the internal oc0x register, no t the oc0x pin. if a system reset occur, the oc0x r egister is reset to ?0?.
ata6614q [datasheet] 9240h?auto?10/14 102 figure 5-30. compare match output unit, schematic the general i/o port function is overridden by the output co mpare (oc0x) from the waveform generator if either of the com0x1:0 bits are set. however, the oc0x pin direction (input or output) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the oc0x pin (ddr_oc 0x) must be set as output before the oc0x value is visible on the pin. the port override func tion is independent of the waveform generation mode. the design of the output compare pin logic allows initialization of the oc0x state before the output is enabled. note that some com0x1:0 bit settings are reserved for certain modes of operation. see section 5.14.9 ?register description? on page 107 . 5.14.6.1 compare output mode and waveform generation the waveform generator uses the com0x1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com0x1:0 = 0 tells the waveform generator that no action on the oc0x register is to be performed on the next compare match. for compare output actions in the non-pwm modes refer to table 5-41 on page 108 . for fast pwm mode, refer to table 5-42 on page 108 , and for phase correct pwm refer to table 5-43 on page 108 . a change of the com0x1:0 bits state will have effect at the first compare match after the bi ts are written. for non-pwm modes, the action can be forced to have immedi ate effect by using the foc0x strobe bits. 5.14.7 modes of operation the mode of operation, i.e., t he behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm02:0) and compare output mode (com0x1:0) bits. the compare output mode bits do not affect the counting sequence, while t he waveform generation mode bits do. the com0x1:0 bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non-p wm modes the com0x1:0 bits control whether the output should be set, cleared, or toggled at a compare match (see section 5.14.6 ?compare match output unit? on page 101 ). for detailed timing information refer to section 5.14.8 ?timer/counter timing diagrams? on page 106 . data bus 0 1 q d comnx1 comnx0 focn ocnx waveform generator q d port q d ddr ocnx pin clk i/o
103 ata6614q [datasheet] 9240h?auto?10/14 5.14.7.1 normal mode the simplest mode of operation is t he normal mode (wgm02:0 = 0). in this mo de the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bottom (0x00). in no rmal operation the timer/counter overflow flag (tov0) will be set in the same timer cl ock cycle as the tcnt0 becomes zero . the tov0 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov0 flag, the timer resolution can be increased by software. there ar e no special cases to consider in the normal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. 5.14.7.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm02:0 = 2), the ocr0 a register is used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcnt0) matches the ocr0a. the ocr0a defines the top value for the counter, hence also its resolution. this mode allo ws greater control of the comp are match output frequency. it also simplifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 5-31 . the counter value (tcnt0) increases until a compare match occurs between tcnt0 and ocr0a, and then counter (tcnt0) is cleared. figure 5-31. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by using the ocf0a flag. if the interrupt is enabled, the interrupt handler routine can be used for updat ing the top value. however, changing top to a value close to bottom when the counter is running with non e or a low prescaler value must be done with care since the ctc mode does not have the double buffering feat ure. if the new value written to ocr0a is lower than the current value of tcnt0, the counter will miss the compare match. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc0a output can be set to to ggle its logical level on each compare match by setting the compare output mode bits to toggle mo de (com0a1:0 = 1). the oc0a value will not be visible on the port pin unless the data direction for the pin is set to out put. the waveform generated will have a maximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero (0x00). the waveform frequency is defined by the following equation: the n variable represents the prescale fa ctor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tov0 flag is set in the same timer clock cycle that the counter counts from max to 0x00. 12 tcntn (comnx1:0 = 1) ocnx (toggle) period 3 ocnx interrupt flag set 4 f ocnx f clk_i/o 2 n 1 ocrnx + () ?? ------------------------------------------------ - =
ata6614q [datasheet] 9240h?auto?10/14 104 5.14.7.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgm02: 0 = 3 or 7) provides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm optio n by its single-slope operation. the counter counts from bottom to top then restarts from bottom. top is defined as 0xff when wgm2:0 = 3, and ocr0a when wgm2:0 = 7. in non-inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tcnt0 and ocr0x, and set at bottom. in inverting compare output mode, the output is set on compare match and cleared at bottom. due to the single-slope operatio n, the operating frequency of the fast pwm mode can be twice as high as the phase correct pwm mode that use dual-sl ope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac applications. high frequency allows physically small sized external components (coils, capacitors), and theref ore reduces total system cost. in fast pwm mode, the counter is incremen ted until the counter value ma tches the top value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 5-32 . the tcnt0 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the sm all horizontal line marks on the tcnt0 slopes represent compare matches between ocr0x and tcnt0. figure 5-32. fast pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the co unter reaches top. if the inte rrupt is enabled, the interrupt handler routine can be used fo r updating the compare value. in fast pwm mode, the compare unit allows generation of pwm waveforms on the oc0x pins. setting the com0x1:0 bits to two will produce a non-inverted pwm and an inverted pwm out put can be generated by setti ng the com0x1:0 to three: setting the com0a1:0 bits to one allows the oc0a pin to toggl e on compare matches if the wgm0 2 bit is set. this option is not available for the oc0b pin (see table 5-45 on page 109 ). the actual oc0x value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by se tting (or clearing) the oc0x register at the compare match between ocr0x and tcnt 0, and clearing (or settin g) the oc0x register at the timer clock cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescale fa ctor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr0a is set equal to bottom, the output will be a narrow sp ike for each max+1 timer clock cycle. setting the ocr0a equal to max will result in a constantly high or low output (depending on the pol arity of the output set by the com0a1:0 bits.) 1234567 tcntn (comnx1:0 = 2) (comnx1:0 = 3) ocnx ocnx period ocrnx update and tovn interrupt flag set ocrnx interrupt flag set f ocnxpwm f clk_i/o n 256 ? ----------------- =
105 ata6614q [datasheet] 9240h?auto?10/14 a frequency (with 50% duty cycle) waveform output in fast pw m mode can be achieved by settin g oc0x to togg le its logical level on each compare match (com0x1:0 = 1). the waveform generated will have a maximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero. this feature is similar to the oc 0a toggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast pwm mode. 5.14.7.4 phase correct pwm mode the phase correct pwm mode (wgm02:0 = 1 or 5) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual-slope operation. the counter count s repeatedly from bottom to top and then from top to bottom. top is defined as 0xff when wgm2:0 = 1, and ocr0a when wgm2:0 = 5. in non- inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tcnt0 and ocr0x while upcounting, and set on the compare match while downcount ing. in inverting output co mpare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmetric feature of the dual-slope pwm modes, t hese modes are preferred for motor control applications. in phase correct pwm mode the counter is incremented until the counter value matches top. when the counter reaches top, it changes the count direct ion. the tcnt0 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 5-33 . the tcnt0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non- inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes represent compare matches between ocr0x and tcnt0. figure 5-33. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches bottom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct pwm mode, the compare unit allows ge neration of pwm waveforms on the oc0x pins. setting the com0x1:0 bits to two will produce a non-inverted pwm. an inverted pwm output can be generated by setting the com0x1:0 to three: setting the com0a0 bits to one allows the oc0a pin to toggle on compare matches if the wgm02 bit is set. this option is not available for the oc0b pin (see table 5-46 on page 109 ). the actual oc0x value will only be visible on the port pin if the data direction for the port pin is set as out put. the pwm waveform is generated by clearing (or setting) th e oc0x register at the compare match between ocr0x and tcnt 0 when the counter increments, and setting (or clearing) the oc0x register at compare match between ocr0x and tcnt 0 when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). 123 tcntn (comnx1:0 = 2) (comnx1:0 = 3) ocnx ocnx period tovn interrupt flag set ocrnx update ocnx interrupt flag set f ocnxpcpwm f clk_i/o n 510 ? ----------------- =
ata6614q [datasheet] 9240h?auto?10/14 106 the extreme values for the ocr0a regist er represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr0a is set equal to bottom, the output will be continuously low and if set equal to max the output will be continuously high for no n-inverted pwm mode. for inverted pwm the output will have the opposite logic values. at the very start of period 2 in figure 5-33 ocnx has a transition from high to lo w even though there is no compare match. the point of this transition is to gua rantee symmetry around bottom. there are tw o cases that give a transition without compare match. ocrnx changes its value from max, like in figure 5-33 . when the ocr0a value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocnx value at max must correspond to the result of an up-counting compare match. the timer starts counting from a value higher than the one in ocrnx, and for that reason misses the compare match and hence the ocnx change that would have happened on the way up. 5.14.8 timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t0 ) is therefore shown as a clock enable signal in the following figures. the figures include inform ation on when interrupt flags are set. figure 5-34 contains timing data for basic timer/counter operation. the figure show s the count sequence close to the max value in all modes other than phase correct pwm mode. figure 5-34. timer/counter timing diagram, no prescaling figure 5-35 shows the same timing data, but with the prescaler enabled. figure 5-35. timer/counter timi ng diagram, with prescaler (f clk_i/o /8) max - 1 clk i/o (clk i/o /1) tcntn tovn clk tn max bottom bottom + 1 max - 1 clk i/o (clk i/o /8) tcntn tovn clk tn max bottom bottom + 1
107 ata6614q [datasheet] 9240h?auto?10/14 figure 5-36 shows the setting of ocf0b in all modes and ocf0a in all modes except ctc mode and pwm mode, where ocr0a is top. figure 5-36. timer/counter timing diagram, setting of ocf0x, with prescaler (f clk_i/o /8) figure 5-37 shows the setting of ocf0a and the clearing of tcnt0 in ctc mode and fast pwm mode where ocr0a is top. figure 5-37. timer/counter timing diagram, clear timer on compar e match mode, with prescaler (f clk_i/o /8) 5.14.9 register description 5.14.9.1 tccr0a ? timer/counter control register a ? bits 7:6 ? com0a1:0: compare match output a mode these bits control the output compare pin (oc0a) behavior. if o ne or both of the com0a1:0 bits are set, the oc0a output overrides the normal port functionality of th e i/o pin it is connected to. however, not e that the data direction register (ddr) bit corresponding to the oc0a pin must be set in order to enable the output driver. ocrnx - 1 clk i/o (clk i/o /8) tcntn ocrnx ocfnx clk tn ocrnx ocrnx + 1 ocrnx value ocrnx + 2 top - 1 clk i/o (clk i/o /8) tcntn (ctc) ocrnx ocfnx clk tn top bottom top bottom + 1 bit 7 6 5 4 3 210 0x24 (0x44) com0a1 com0a0 com0b1 com0b0 ? ? wgm01 wgm00 tccr0a read/write r/w r/w r/w r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0
ata6614q [datasheet] 9240h?auto?10/14 108 when oc0a is connected to the pin, the function of the com0a1:0 bits depends on the wgm02:0 bit setting. table 5-41 shows the com0a1:0 bit functionality when the wgm 02:0 bits are set to a normal or ctc mode (non-pwm). table 5-42 shows the com0a1:0 bit functionality when the wgm01:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0a equals top and com0a1 is set. in this case, the compare match is ignored, but the set or clear is done at bottom. see section 5.14.7.3 ?fast pwm mode? on page 104 for more details. table 5-43 shows the com0a1:0 bit functionality when the wgm02:0 bits are set to phase correct pwm mode. note: 1. a special case occurs when ocr0a equals top and com0a1 is set. in this case, the compare match is ignored, but the set or clear is done at top. see section 5.15.9.4 ?phase correc t pwm mode? on page 126 for more details. ? bits 5:4 ? com0b1:0: compare match output b mode these bits control the output compare pin (oc0b) behavior. if o ne or both of the com0b1:0 bits are set, the oc0b output overrides the normal port functionality of th e i/o pin it is connected to. however, not e that the data direction register (ddr) bit corresponding to the oc0b pin must be set in order to enable the output driver. when oc0b is connected to the pin, the function of the com0b1:0 bits depends on the wgm02:0 bit setting. table 5-44 shows the com0b1:0 bit functionality when the wgm 02:0 bits are set to a normal or ctc mode (non-pwm). table 5-41. compare output mode, non-pwm mode com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 0 1 toggle oc0a on compare match 1 0 clear oc0a on compare match 1 1 set oc0a on compare match table 5-42. compare output mode, fast pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 0 1 wgm02 = 0: normal port oper ation, oc0a disconnected. wgm02 = 1: toggle oc0a on compare match. 1 0 clear oc0a on compare match, set oc0a at bottom, (non-inverting mode). 1 1 set oc0a on compare match, clear oc0a at bottom, (inverting mode). table 5-43. compare output mode, phase correct pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 0 1 wgm02 = 0: normal port operation, oc0a disconnected. wgm02 = 1: toggle oc0a on compare match. 1 0 clear oc0a on compare match when up-counting. set oc0a on compare match when down-counting. 1 1 set oc0a on compare match when up-counting. clear oc0a on compare match when down-counting. table 5-44. compare output mode, non-pwm mode com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 0 1 toggle oc0b on compare match 1 0 clear oc0b on compare match 1 1 set oc0b on compare match
109 ata6614q [datasheet] 9240h?auto?10/14 table 5-45 shows the com0b1:0 bit functionality when the wgm02:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0b equals top and com0b1 is set. in this case, the compare match is ignored, but the set or clear is done at top. see section 5.14.7.3 ?fast pwm mode? on page 104 for more details. table 5-46 shows the com0b1:0 bit functionality when the wgm02:0 bits are set to phase correct pwm mode. note: 1. a special case occurs when ocr0b equals top and com0b1 is set. in this case, the compare match is ignored, but the set or clear is done at top. see section 5.14.7.4 ?phase correc t pwm mode? on page 105 for more details. ? bits 3, 2 ? res: reserved bits these bits are reserved bits in the atmega328p and will always read as zero. ? bits 1:0 ? wgm01:0: waveform generation mode combined with the wgm02 bit found in the t ccr0b register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and w hat type of waveform generation to be used, see table 5-47 . modes of operation supported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes (see section 5.14.7 ?modes of operation? on page 102 ). notes: 1. max = 0xff 2. bottom = 0x00 table 5-45. compare output mode, fast pwm mode (1) com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 0 1 reserved 1 0 clear oc0b on compare match, set oc0b at bottom, (non-inverting mode) 1 1 set oc0b on compare match, clear oc0b at bottom, (inverting mode). table 5-46. compare output mode, phase correct pwm mode (1) com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 0 1 reserved 1 0 clear oc0b on compare match when up-counting. set oc0b on compare match when down-counting. 1 1 set oc0b on compare match when up-counting. clear oc0b on compare match when down-counting. table 5-47. waveform generation mode bit description mode wgm02 wgm01 wgm00 timer/counter mode of operation top update of ocrx at tov flag set on (1)(2) 0 0 0 0 normal 0xff immediate max 1 0 0 1 pwm, phase correct 0xff top bottom 2 0 1 0 ctc ocra immediate max 3 0 1 1 fast pwm 0xff bottom max 4 1 0 0 reserved ? ? ? 5 1 0 1 pwm, phase correct ocra top bottom 6 1 1 0 reserved ? ? ? 7 1 1 1 fast pwm ocra bottom top
ata6614q [datasheet] 9240h?auto?10/14 110 5.14.9.2 tccr0b ? timer/count er control register b ? bit 7 ? foc0a: force output compare a the foc0a bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr0b is written when operating in pwm mode. when writing a logical one to the foc0a bi t, an immediate compare match is forced on the waveform generation unit. the oc0a output is changed according to its com0a1:0 bits setting. note that the foc0a bit is implemented as a strobe. therefor e it is the value present in the com0a1:0 bits that determ ines the effect of the forced compare. a foc0a strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0a as top. the foc0a bit is always read as zero. ? bit 6 ? foc0b: force output compare b the foc0b bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr0b is written when operating in pwm mode. when writing a logical one to the foc0b bi t, an immediate compare match is forced on the waveform generation unit. the oc0b output is changed according to its com0b1:0 bits setting. note that the foc0b bit is implemented as a strobe. therefor e it is the value present in the com0b1:0 bits that determ ines the effect of the forced compare. a foc0b strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0b as top. the foc0b bit is always read as zero. ? bits 5:4 ? res: reserved bits these bits are reserved bits in the atmega328p and will always read as zero. ? bit 3 ? wgm02: waveform generation mode see the description in the section 5.14.9.1 ?tccr0a ? timer/counter control register a? on page 107 . ? bits 2:0 ? cs02:0: clock select the three clock se lect bits select the clock source to be used by the timer/counter. if external pin modes are used for the timer/counter0, transit ions on the t0 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. bit 7 6 5 4 3 210 0x25 (0x45) foc0a foc0b ? ? wgm02 cs02 cs01 cs00 tccr0b read/write w w r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 5-48. clock select bit description cs02 cs01 cs00 description 0 0 0 no clock source (timer/counter stopped) 0 0 1 clk i/o /(no prescaling) 0 1 0 clk i/o /8 (from prescaler) 0 1 1 clk i/o /64 (from prescaler) 1 0 0 clk i/o /256 (from prescaler) 1 0 1 clk i/o /1024 (from prescaler) 1 1 0 external clock source on t0 pin. clock on falling edge. 1 1 1 external clock source on t0 pin. clock on rising edge.
111 ata6614q [datasheet] 9240h?auto?10/14 5.14.9.3 tcnt0 ? timer/counter register the timer/counter register gives direct a ccess, both for read and write operations, to the timer/counter unit 8-bit counter. writing to the tcnt0 register blocks (re moves) the compare match on the followin g timer clock. modifying the counter (tcnt0) while the counter is running, introduces a risk of missing a compare match between tcnt0 and the ocr0x registers. 5.14.9.4 ocr0a ? output compare register a the output compare register a contains an 8-bit value that is continuou sly compared with the counter value (tcnt0). a match can be used to generate an output compare interrup t, or to generate a waveform output on the oc0a pin. 5.14.9.5 ocr0b ? output compare register b the output compare register b contains an 8-bit value that is continuou sly compared with the counter value (tcnt0). a match can be used to generate an output compare interrup t, or to generate a waveform output on the oc0b pin. 5.14.9.6 timsk0 ? timer/counter interrupt mask register ? bits 7..3 ? res: reserved bits these bits are reserved bits in the atmega328p and will always read as zero. ? bit 2 ? ocie0b: timer/counter outp ut compare match b interrupt enable when the ocie0b bit is written to one, and the i-bit in the status r egister is set, the timer/c ounter compare match b interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/co unter occurs, i.e., when the ocf0b bit is set in the timer/counter interrupt flag register ? tifr0. ? bit 1 ? ocie0a: timer/counter0 outp ut compare match a interrupt enable when the ocie0a bit is written to one, and the i-bit in the status register is set, the timer/counter0 compare match a interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/coun ter0 occurs, i.e., when the ocf0a bit is set in the timer/counter 0 interrupt flag register ? tifr0. ? bit 0 ? toie0: timer/counter0 overflow interrupt enable when the toie0 bit is written to one, an d the i-bit in the status register is se t, the timer/counter0 overflow interrupt is enabled. the corresponding interrupt is exec uted if an overflow in timer/counter0 oc curs, i.e., when the tov0 bit is set in the timer/counter 0 interrupt flag register ? tifr0. bit 76543210 0x26 (0x46) tcnt0[7:0] tcnt0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x27 (0x47) ocr0a[7:0] ocr0a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x28 (0x48) ocr0b[7:0] ocr0b read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543 210 (0x6e)?????ocie0bocie0atoie0timsk0 read/write rrrrrr/wr/wr/w initial value00000 000
ata6614q [datasheet] 9240h?auto?10/14 112 5.14.9.7 tifr0 ? timer/counter 0 interrupt flag register ? bits 7..3 ? res: reserved bits these bits are reserved bits in the atmega328p and will always read as zero. ? bit 2 ? ocf0b: timer/counter 0 output compare b match flag the ocf0b bit is set when a compare match occurs between the timer/counter and the dat a in ocr0b ? output compare register0 b. ocf0b is cleared by hardw are when executing the corresponding interrupt handling vector. alternatively, ocf0b is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0b (t imer/counter compare b match interrupt enable), and ocf0b are set, the time r/counter compare match interrupt is executed. ? bit 1 ? ocf0a: timer/counter 0 output compare a match flag the ocf0a bit is set when a compare match occurs between th e timer/counter0 and the data in ocr0a ? output compare register0. ocf0a is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, ocf0a is cleared by writing a logic one to t he flag. when the i-bit in sreg, ocie0a (timer/counter0 compare match interrupt enable), and ocf0a are set, the timer/counter0 compare match interrupt is executed. ? bit 0 ? tov0: timer/counter0 overflow flag the bit tov0 is set when an overflow occurs in timer/co unter0. tov0 is cleared by hardware when executing the corresponding interrupt handling vector. alter natively, tov0 is cleared by writing a logic one to the flag. when the sreg i- bit, toie0 (timer/counter0 overflow interr upt enable), and tov0 are set, the timer/ counter0 overflow interrupt is executed. the setting of this flag is dependent of the wgm02:0 bit setting. refer to table 5-47 on page 109 . bit 76543210 0x15 (0x35) ? ? ? ? ? ocf0b ocf0a tov0 tifr0 read/write r r r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0
113 ata6614q [datasheet] 9240h?auto?10/14 5.15 16-bit timer/counter1 with pwm 5.15.1 features true 16-bit design (i.e., allows 16-bit pwm) two independent output compare units double buffered out put compare registers one input capture unit input capture noise canceler clear timer on compare match (auto reload) glitch-free, phase correct pulse width modulator (pwm) variable pwm period frequency generator external event counter four independent interrupt sources (tov1, ocf1a, ocf1b, and icf1) 5.15.2 overview the 16-bit timer/counter unit allows a ccurate program execution timing (event management), wave generation, and signal timing measurement. most register and bit references in this section are written in general form. a lower case ?n? replaces the timer/counter number, and a lower case ?x? replaces the output compare unit channel. however, when us ing the register or bit defines in a program, the precise form must be us ed, i.e., tcnt1 for accessing timer/ counter1 counter value and so on. a simplified block diagram of the 16-bit timer/counter is shown in figure 5-38 . the device-specific i/o register and bit locations are listed in the section 5.15.11 ?register description? on page 131 . the prtim1 bit in section 5.9.11.3 ?prr ? power reduction register? on page 63 must be written to zero to enable timer/counter1 module.
ata6614q [datasheet] 9240h?auto?10/14 114 figure 5-38. 16-bit time r/counter block diagram (1) note: 1. refer to table 5-31 on page 89 and table 5-37 on page 94 for timer/counter1 pin placement and description. 5.15.2.1 registers the timer/counter (tcnt1), output compare registers (ocr1a/b), and input capture register (icr1) are all 16-bit registers. special procedures must be followed when access ing the 16-bit registers. these procedures are described in section 5.15.3 ?accessing 16-b it registers? on page 115 . the timer/counter control registers (tccr1a/b) are 8-bit registers and have no cpu access restrictions . interrupt requests (abbreviated to int.req. in the figure) signals are all visib le in the timer interrupt flag register (tifr1). all interrupts are individually masked with the timer interrupt mask register (timsk1). tifr1 and timsk1 are not shown in the figure. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the t1 pin. th e clock select logic block controls which clock source and edge the timer/ counter uses to increment (o r decrement) its value. the timer/counter is inactive when no clock source is selected. the out put from the clock select logic is referred to as the timer clock (clk t1 ). the double buffered output compare register s (ocr1a/b) are compared with the timer/counter value at all time. the result of the compare can be used by the waveform generator to ge nerate a pwm or variable frequency output on the output compare pin (oc1a/b). see section 5.15.7 ?output compare units? on page 120 . the compare match event will also set the compare match flag (ocf1a/b) which can be used to generate an output compare interrupt request. the input capture register can capture the timer/counter value at a given external (edge triggered) event on either the input capture pin (icp1) or on the analog comparator pins (see section 5.22 ?analog comparator? on page 223 ). control logic tcntn timer/counter count clear direction clk tn ocrna ocrnb icrn tccrna tccrnb = edge detector (from prescaler) clock select top bottom tovn (int. req.) ocna (int. req.) tn waveform generation fixed top value data bus = = = 0 ocna ocnb (int. req.) waveform generation noise canceler ocnb (from analog comparator output) icfn (int. req.) edge detector icpn
115 ata6614q [datasheet] 9240h?auto?10/14 the input capture unit includes a digital filtering unit (noise c anceler) for reducing the chance of capturing noise spikes. th e top value, or maximum timer/counter value, can in some m odes of operation be defined by ei ther the ocr1a register, the icr1 register, or by a set of fixed values. when using ocr1a as top value in a pwm mode, the ocr1a register can not be used for generating a pwm output. however, the top value will in this case be double buffered allowing the top value to be changed in run time. if a fixed top value is required, the icr1 register can be used as an alternative, freeing the ocr1a to be used as pwm output. 5.15.2.2 definitions the definitions in table 5-49 are also used extensively throughout the section. 5.15.3 accessing 16-bit registers the tcnt1, ocr1a/b, and icr1 are 16-bit registers that can be accessed by the avr ? cpu via the 8-bit data bus. the 16- bit register must be byte accessed using two read or write ope rations. each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16-bit access. the same te mporary register is shared between all 16-bit registers within each 16-bit timer. accessing the low byte triggers the 16-bit read or write operation. when the low byte of a 16-bit register is written by the cpu, the high byte stored in the temporary register, and the low byte written are both copied into t he 16-bit register in the same clock cycle. when the low byte of a 16-bit register is read by t he cpu, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. not all 16-bit accesses uses the temporary register for the hi gh byte. reading the ocr1a/b 16-b it registers does not involve using the temporary register. to do a 16-bit write, the high byte must be writte n before the low byte. for a 16-bit read, the l ow byte must be read before the high byte. the following code examples show how to access the 16-bi t timer registers assuming that no interrupts updates the temporary register. the same principle can be used directly for accessing the ocr1a/b and i cr1 registers. note that when using ?c?, the compiler handles the 16-bit access. table 5-49. definitions case definition bottom the counter reaches the bottom when it becomes 0x0000. max the counter reaches its maximum when it becomes 0xffff (decimal 65535). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be one of the fixed values: 0x00ff, 0x01ff, or 0x03ff, or to the value stored in the ocr1a or icr1 register. the assi gnment is dependent of the mode of operation. assembly code examples (1) ... ; set tcnt 1 to 0x01ff ldi r17,0x01 ldi r16,0xff out tcnt 1 h,r17 out tcnt 1 l,r16 ; read tcnt 1 into r17:r16 in r16,tcnt 1 l in r17,tcnt 1 h ... c code examples (1) unsigned int i; ... /* set tcnt 1 to 0x01ff */ tcnt 1 = 0x1ff; /* read tcnt 1 into i */ i = tcnt 1 ; ... note: 1. see section 5.5 ?about code examples? on page 32 . for i/o registers located in extended i/o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ? sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? comb ined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?.
ata6614q [datasheet] 9240h?auto?10/14 116 the assembly code example returns the tcnt1 value in the r17:r16 register pair. it is important to notice that accessing 16-bit registers are atomic operations. if an interrupt occurs between the two instructions accessing the 16-bit register , and the interrupt code updates the temp orary register by accessing the same or any other of the 16-bit timer registers, then the result of the access outside the in terrupt will be corrupted. therefore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. the following code examples show how to do an atomic read of the tcnt1 register conten ts. reading any of the ocr1a/b or icr1 registers can be done by using the same principle. the assembly code example returns the tcnt1 value in the r17:r16 register pair. assembly code example (1) tim16_readtcnt 1 : ; save global interrupt flag in r18,sreg ; disable interrupts cli ; read tcnt 1 into r17:r16 in r16,tcnt 1 l in r17,tcnt 1 h ; restore global interrupt flag out sreg,r18 ret c code example (1) unsigned int tim16_readtcnt 1 ( void ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ _cli(); /* read tcnt 1 into i */ i = tcnt 1 ; /* restore global interrupt flag */ sreg = sreg; return i; } note: 1. see section 5.5 ?about code examples? on page 32 . for i/o registers located in extended i/o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?.
117 ata6614q [datasheet] 9240h?auto?10/14 the following code examples show how to do an atomic writ e of the tcnt1 register conten ts. writing any of the ocr1a/b or icr1 registers can be done by using the same principle. the assembly code example requires that the r17:r16 register pair contains the value to be written to tcnt1. 5.15.3.1 reusing the temporary high byte register if writing to more than one 16-bit regist er where the high byte is the same for a ll registers written, then the high byte only needs to be written once. however, note that the same rule of atomic operation described pr eviously also applies in this case. 5.15.4 timer/counter clock sources the timer/counter can be clocked by an internal or an extern al clock source. the clock sour ce is selected by the clock select logic which is controlled by the clock select (cs12:0) bits located in the timer/counter control register b (tccr1b). for details on clock sources and prescaler, see section 5.16 ?timer/count er0 and timer/counter1 prescalers? on page 137 . assembly code example (1) tim16_writetcnt 1 : ; save global interrupt flag in r18,sreg ; disable interrupts cli ; set tcnt 1 to r17:r16 out tcnt 1 h,r17 out tcnt 1 l,r16 ; restore global interrupt flag out sreg,r18 ret c code example (1) void tim16_writetcnt 1 ( unsigned int i ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ _cli(); /* set tcnt 1 to i */ tcnt 1 = i; /* restore global interrupt flag */ sreg = sreg; } note: 1. see section 5.5 ?about code examples? on page 32 . for i/o registers located in extended i /o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ?sbi? in structions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?.
ata6614q [datasheet] 9240h?auto?10/14 118 5.15.5 counter unit the main part of the 16-bit timer/counter is the programmable 16-bit bi-directional counter unit. figure 5-39 shows a block diagram of the counter and its surroundings. figure 5-39. counter unit block diagram signal description (internal signals): count increment or decrement tcnt1 by 1. direction select between increment and decrement. clear clear tcnt1 (set all bits to zero). clk t1 timer/counter clock. top signalize that tcnt1 has reached maximum value. bottom signalize that tcnt1 has reached minimum value (zero). the 16-bit counter is mapped into two 8-bit i/o memory locations: counter high (tcnt1h) containing the upper eight bits of the counter, and counter low (tcnt1l) containing the lower eight bits. the tcnt1h register can only be indirectly accessed by the cpu. when the cpu does an access to t he tcnt1h i/o location, the cpu accesses the high byte temporary register (temp). th e temporary register is updated with the tcnt1h value when the tcnt1l is read, and tcnt1h is updated with the tem porary register value when tcnt1l is written. this allows the cpu to read or write the entire 16-bit counter value within one clock cycle via the 8- bit data bus. it is im portant to notice that there are special cas es of writing to the tcnt1 regist er when the counter is counti ng that will give unpredictable results. the special cases are described in the sections where they are of importance. depending on the mode of operation us ed, the counter is cleared, incr emented, or decremented at each timer clock (clk t1 ). the clk t1 can be generated from an external or internal clock source, selected by the clock select bits (cs12:0). when no clock source is selected (cs12:0 = 0) the timer is stopp ed. however, the tcnt1 value can be accessed by the cpu, independent of whether clk t1 is present or not. a cpu write overrides (has prio rity over) all counter cl ear or count operations. the counting sequence is determined by the setting of the waveform generation mode bits (wgm13:0) located in the timer/counter c ontrol registers a and b (tccr1a and tccr1b). there are close connections between how the counter behaves (counts) and how waveforms ar e generated on the output compare out puts oc1x. for more details about advanced counting sequences and waveform generation, see section 5.15.9 ?modes of operation? on page 123 . the timer/counter overflow flag (tov1) is set according to t he mode of operation selected by the wgm13:0 bits. tov1 can be used for generating a cpu interrupt. 5.15.6 input capture unit the timer/counter incorporates an input capture unit that can c apture external events and give them a time-stamp indicating time of occurrence. the external signal indicating an ev ent, or multiple events, can be applied via the icp1 pin or alternatively, via the analog-comparator unit. the time-stamps can then be used to calculate freque ncy, duty-cycle, and other features of the signal applied. alternatively the time-stamps can be used for creating a log of the events. the input capture unit is illustrated by the block diagram shown in figure 5-40 . the elements of the block diagram that are not directly a part of the input capture unit are gray shade d. the small ?n? in register and bit names indicates the timer/counter number. bottom top tovn (int. req.) data bus (8-bit) control logic tcntnh (8-bit) tcntnh (16-bit counter) tcntnl (8-bit) temp (8-bit) clk tn clear count direction edge detector (from prescaler) clock select tn
119 ata6614q [datasheet] 9240h?auto?10/14 figure 5-40. input capture unit block diagram when a change of the logic level (an event) occurs on the input capture pin (icp1), alternativ ely on the analog comparator output (aco), and this change confirms to the setting of the edge detector, a captur e will be triggered. when a capture is triggered, the 16-bit value of the counter (tcnt1) is written to the input capture register (icr1). the input capture flag (icf 1) is set at the same system clock as the tcnt1 value is copied into icr1 register. if enabled (i cie1 = 1), the input capture flag generates an input capture interrupt. the ic f1 flag is automatically cleared when t he interrupt is execut ed. alternatively the icf1 flag can be cleared by software by wr iting a logical one to its i/o bit location. reading the 16-bit value in the input capt ure register (icr1) is done by first read ing the low byte (icr1l) and then the high byte (icr1h). when the low byte is read the high byte is co pied into the high byte temporary register (temp). when the cpu reads the icr1h i/o location it will access the temp register. the icr1 register can only be written when using a waveform gener ation mode that utilizes the ic r1 register for defining the counter?s top value. in these cases the waveform generation mode (wgm13:0) bits must be set before the top value can be written to the icr1 register. when writing the icr1 register the high byte must be written to the icr1h i/o location before the low byte is written to icr1l. for more information on how to access the 16-bit registers refer to section 5.15.3 ?accessing 16-b it registers? on page 115 . 5.15.6.1 input capture trigger source the main trigger source for the input capture unit is the in put capture pin (icp1). timer/co unter1 can alternatively use the analog comparator output as trigger source for the input capture unit. the analog comparator is selected as trigger source by setting the analog comparator input capture (acic) bit in the analog comparator control and status register (acsr). be aware that changing trigger source can tr igger a capture. the input capture flag must therefor e be cleared after the change. both the input capture pin (icp1) and t he analog comparator output (aco) inputs are sampled using the same technique as for the t1 pin ( figure 5-51 on page 137 ). the edge detector is also identical. however, when the noise canceler is enabled, additional logic is inserted before the edge detector, which in creases the delay by four system clock cycles. note that the input of the noise canceler and edge detector is always enabled unless the timer/counter is set in a waveform generation mode that uses icr1 to define top. an input capture can be triggered by softw are by controlling the port of the icp1 pin. icfn (int. req.) icrnl (8-bit) icrnh (8-bit) icrn (16-bit register) temp (8-bit) tcntnl (8-bit) tcntnh (8-bit) tcntn (16-bit counter) data bus (8-bit) noise canceler analog comparator edge detector icnc acic* aco* write + - ices icpn
ata6614q [datasheet] 9240h?auto?10/14 120 5.15.6.2 noise canceler the noise canceler improves noise immunity by using a simple digital filtering scheme. the noise canceler input is monitored over four samples, and all four must be equal for changing the output that in turn is used by the edge detector. the noise canceler is enabled by setting the input capture noise canceler (icnc1) bit in time r/counter control register b (tccr1b). when enabled the noise canceler introduces additional four system clock cycles of delay from a change applied to the input, to the update of the icr1 register. the noise canc eler uses the system clock and is therefore not affected by the prescaler. 5.15.6.3 using the input capture unit the main challenge when using the input capture unit is to assign enough processor capacity for handling the incoming events. the time between two events is cr itical. if the processor has not read the ca ptured value in the icr1 register before the next event occurs, the icr1 will be overwritten with a new valu e. in this case the result of the capture will be incorrect. when using the input capture interrupt, the icr1 register should be read as early in the interrupt handler routine as possible. even though the input capture interrupt has relatively high pr iority, the maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests. using the input capture unit in any mode of operation when the top value (resolution) is actively changed during operation, is not recommended. measurement of an external signal?s duty cycle requires that the trigger edge is changed after each capture. changing the edge sensing must be done as early as possible after the icr1 register has been read. after a change of the edge, the input capture flag (icf1) must be cleared by software (writing a logi cal one to the i/o bit location). for measuring frequency only, the clearing of the icf1 flag is not required (if an interrupt handler is used). 5.15.7 output compare units the 16-bit comparator continuously comp ares tcnt1 with the output compare register (ocr1x). if tcnt equals ocr1x the comparator signals a match. a ma tch will set the output compare flag (o cf1x) at the next timer clock cycle . if enabled (ocie1x = 1), the output compare flag gen erates an output compare in terrupt. the ocf1x flag is automatically cleared when the interrupt is executed. alternatively the ocf1x flag can be cleared by software by writing a logical one to its i/o bit location. the waveform generator uses the match signal to generate an output according to operating mode set by the waveform generation mode (wgm13:0) bits and compare output mode (com1x1:0) bits. the top and bottom signals are used by the waveform generator for ha ndling the special cases of the extreme va lues in some modes of operation (see section 5.15.9 ?modes of operation? on page 123 ). a special feature of output com pare unit a allows it to define the timer/coun ter top value (i.e., coun ter resolution). in addition to the counter resolution, the top value defines the period time for waveforms generated by the waveform generator. figure 5-41 shows a block diagram of the output compare unit. the small ?n? in the register and bit names indicates the device number (n = 1 for timer/counter 1), and the ?x? indica tes output compare unit (a/b). the elements of the block diagram that are not directly a part of the output compare unit are gray shaded.
121 ata6614q [datasheet] 9240h?auto?10/14 figure 5-41. output comp are unit, block diagram the ocr1x register is double buffered wh en using any of the twelve pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the do uble buffering is disabled. the double buffering synchronizes the update of the ocr1x compare regist er to either top or bottom of t he counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby maki ng the output glitch-free. the ocr1x register access may seem co mplex, but this is not case. when th e double buffering is enabled, the cpu has access to the ocr1x buffer register, and if double buffering is disabled the cpu will access th e ocr1x directly. the content of the ocr1x (buffer or compare) register is only changed by a write operation (the timer/ counter does not update this register automatically as the tcnt1 and i cr1 register). therefore ocr1x is not r ead via the high byte temporary register (temp). however, it is a good practice to read the low byte fi rst as when accessing other 16-b it registers. writing the ocr1x registers must be done via the temp register since the compare of all 16 bits is done continuously. the high byte (ocr1xh) has to be written first. when the high byte i/o location is written by the cpu, th e temp register will be updated by the value written. then when the low byte (ocr1xl) is written to the lowe r eight bits, the high byte will be copied into the upper 8-bits of either the ocr1x buffer or ocr1x compar e register in the same system clock cycle. for more information of how to access the 16-bit registers refer to section 5.15.3 ?accessing 16-bit registers? on page 115 . 5.15.7.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (foc1x) bit. forc ing compare match will not set the ocf1x flag or reload/clear the timer, but the oc1x pin will be updated as if a real compare match had occurred (the com11:0 bits settings define w hether the oc1x pin is set, cleared or toggled). 5.15.7.2 compare match blocking by tcnt1 write all cpu writes to the tcnt1 register will block any compare matc h that occurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocr1x to be initialized to the same value as tcnt1 without triggering an interrupt when the timer/counter clock is enabled. ocrnxl buf. (8-bit) ocrnxh buf. (8-bit) ocrnx buffer (16-bit register) temp (8-bit) ocrnxl (8-bit) ocfnx (int. req.) ocrnxh (8-bit) ocrnx (16-bit register) = (16-bit comparator) wgmn3:0 comnx1:0 waveform generator tcntnl (8-bit) tcntnh (8-bit) tcntn (16-bit counter) data bus (8-bit) ocnx top bottom
ata6614q [datasheet] 9240h?auto?10/14 122 5.15.7.3 using the ou tput compare unit since writing tcnt1 in any mode of ope ration will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt1 when using any of the output compare channels, independent of whether the timer/counter is running or not. if the value written to tcnt1 equals the ocr1x value, the com pare match will be missed, resulting in incorrect waveform generation. do not write the tcnt1 equa l to top in pwm modes with variable top values. the compare match for the top will be ignored and the counter will continue to 0xffff. si milarly, do not write the tcnt1 value equal to bottom when the counter is downcounting. the setup of the oc1x should be performed bef ore setting the data direction register for the port pin to output. the easiest way of setting the oc1x value is to use the force output co mpare (foc1x) strobe bits in normal mode. the oc1x register keeps its value even when changing between waveform generation modes. be aware that the com1x1:0 bits are not double buffered together with the compar e value. changing the com1x1:0 bits will take effect immediately. 5.15.8 compare match output unit the compare output mode (com1x1:0) bits have two functi ons. the waveform generator uses the com1x1:0 bits for defining the output compare (oc1x) state at the next compare match. secondly the com1x1:0 bits control the oc1x pin output source. figure 5-42 shows a simplified schematic of the logic affected by the com1x1:0 bit sett ing. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the com1x1:0 bits ar e shown. when referring to the oc1x state, the reference is for the internal oc1x register, not the oc1x pin. if a system rese t occur, the oc1x register is reset to ?0?. figure 5-42. compare match output unit, schematic the general i/o port function is overridden by the output co mpare (oc1x) from the waveform generator if either of the com1x1:0 bits are set. however, the oc1x pin direction (input or output) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the oc1x pin (ddr_oc 1x) must be set as output before the oc1x value is visible on the pin. the port override function is generally independent of the wave form generation mode, but there are some exceptions. refer to table 5-50 , table 5-51 and table 5-52 for details. the design of the output compare pin logic allows initialization of the oc1x state before the output is enabled. note that some com1x1:0 bit settings are reserved for certain modes of operation. see section 5.15.11 ?register description? on page 131 . the com1x1:0 bits have no effect on the input capture unit. data bus 0 1 q d comnx1 comnx0 focnx ocnx waveform generator q d port q d ddr ocnx pin clk i/o
123 ata6614q [datasheet] 9240h?auto?10/14 5.15.8.1 compare output mode and waveform generation the waveform generator uses the com1x1:0 bits differentl y in normal, ctc, and pwm modes. for all modes, setting the com1x1:0 = 0 tells the waveform generator that no action on the oc1x register is to be performed on the next compare match. for compare output actions in the non-pwm modes refer to table 5-50 on page 131 . for fast pwm mode refer to table 5-51 on page 131 , and for phase correct and phase and frequency correct pwm refer to table 5-52 on page 132 . a change of the com1x1:0 bits state will have effect at the first compare match after the bi ts are written. for non-pwm modes, the action can be forced to have immedi ate effect by using the foc1x strobe bits. 5.15.9 modes of operation the mode of operation, i.e., t he behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm13:0) and compare output mode (com1x1:0) bits. the compare output mode bits do not affect the counting sequence, while t he waveform generation mode bits do. the com1x1:0 bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non-p wm modes the com1x1:0 bits control whether the output should be set, cl eared or toggle at a compare match (see section 5.15.8 ?compare match output unit? on page 122 ). for detailed timing information refer to section 5.15.10 ?timer/counter timing diagrams? on page 129 . 5.15.9.1 normal mode the simplest mode of operation is t he normal mode (wgm13:0 = 0). in this mo de the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 16-bit value (max = 0xffff) and then restarts from the bottom (0x0000). in normal operation the timer/counter overflow flag (tov1) will be set in the same timer clock cycle as the tcnt1 becomes zero. the tov1 flag in this ca se behaves like a 17th bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov1 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the input capture unit is easy to use in normal mode. howeve r, observe that the maximum interval between the external events must not exceed the resolution of the counter. if the interval between events are too long, the timer overflow interrupt or the prescaler must be used to exte nd the resolution for the capture unit. the output compare units can be used to generate interrupts at some given ti me. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. 5.15.9.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm13:0 = 4 or 12) , the ocr1a or icr1 register are used to manipulate the counter resolution. in ctc mode the count er is cleared to zero when the counter value (tcnt1) matches either the ocr1a (wgm13:0 = 4) or the icr1 (wgm13:0 = 12) . the ocr1a or icr1 define the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 5-43 . the counter value (tcnt1) increases until a compare match occurs with either ocr1a or icr1, and then counter (tcnt1) is cleared. figure 5-43. ctc mode, timing diagram 12 tcntn (comna1:0 = 1) ocna (toggle) period 3 ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 4
ata6614q [datasheet] 9240h?auto?10/14 124 an interrupt can be generated at each time the counter value re aches the top value by either using the ocf1a or icf1 flag according to the register used to define the top value. if th e interrupt is enabled, the inte rrupt handler routine can be used for updating the top value. however, changing the top to a value close to bottom when the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr1a or icr1 is lower than the current value of tcnt1, the counter will miss the compare match. the counter will then have to count to its maximum value (0xfff f) and wrap around starting at 0x0000 before the compare match can occur. in many cases this f eature is not desirable. an alternative wi ll then be to use the fast pwm mode using ocr1a for defining top (wgm13:0 = 15) since the ocr1a then will be double buffered. for generating a waveform output in ctc mode, the oc1a output can be set to to ggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com1a1:0 = 1). the oc1a value will not be visible on the port pin unless the data direction for the pin is set to output (ddr_oc1a = 1). the waveform generated will have a maximum frequency of f oc1a = f clk_i/o /2 when ocr1a is set to zero (0x0000). the waveform frequency is defined by the following equation: the n variable represents the prescaler fa ctor (1, 8, 64, 256, or 1024). as for the normal mode of opera tion, the tov1 flag is set in the same timer clock cycle that the counter counts from max to 0x0000. 5.15.9.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgm13:0 = 5, 6, 7, 14, or 15) provides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm options by its single-slope operation. the counter counts from bottom to top then restarts from bottom. in non-inverting compare output mode, the output compare (oc1x) is cleared on the compare match between tcnt1 and ocr1x, and set at bottom. in inverting compare output mode output is set on compare match a nd cleared at bottom. due to the single -slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase correct and phase and frequency correct pwm modes that use dual-slope operation. this high frequency makes the fast pwm mode well suited for power regula tion, rectification, and dac applications. high frequency allows physically small sized ex ternal components (coils, capacitors), hence reduces total system cost. the pwm resolution for fast pwm can be fixed to 8-, 9-, or 10-bit, or defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution in bits can be calculated by using the following equation: in fast pwm mode the counter is incremented until the count er value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgm13:0 = 5, 6, or 7), the value in icr1 (wgm13:0 = 14), or the value in ocr1a (wgm13:0 = 15). the counter is then cleared at the following timer clock cycl e. the timing diagram for th e fast pwm mode is shown in figure 5-44 . the figure shows fast pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the timing diagram shown as a histogram for illustrating the single-slo pe operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the t cnt1 slopes represent compare matches between ocr1x and tcnt1. the oc1x interrupt flag will be set when a compare match occurs. f ocna f clk_i/o 2 n 1 ocrna + () ?? ------------------------------------------------- - = r fpwm top 1 + () log 2 () log ---------------------------------- =
125 ata6614q [datasheet] 9240h?auto?10/14 figure 5-44. fast pwm mode, timing diagram the timer/counter overflow flag (tov1) is set each time the coun ter reaches top. in addition the oc1a or icf1 flag is set at the same timer clock cycle as tov1 is set when either ocr1a or icr1 is used for defining the to p value. if one of the interrupts are enabled, the interrupt handler routine can be used for updating the top and compare values. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcnt1 and the ocr1x. note that when using fixed top valu es the unused bits are masked to zero when any of the ocr1x registers are written. the procedure for updating icr1 differs from updating ocr1a wh en used for defining the top value. the icr1 register is not double buffered. this means that if icr1 is changed to a low value when the counter is running with none or a low prescaler value, there is a risk that the new icr1 value written is lower than the cu rrent value of tcnt1. the result will then be that the counter will miss the compare match at the top val ue. the counter will then have to count to the max value (0xffff) and wrap around starting at 0x0000 before the comp are match can occur. the ocr1a register however, is double buffered. this feature allows the ocr1a i/o location to be written anytime. w hen the ocr1a i/o location is written the value written will be put into the ocr1a buffer register. the ocr1a compare register will then be updated with the value in the buffer register at the next timer clock cycle the tcnt1 matches top. the upd ate is done at the same timer clock cycle as the tcnt1 is cleared and the tov1 flag is set. using the icr1 register for defining top works well when using fixed top values. by using icr1, the ocr1a register is free to be used for generating a pwm output on oc1a. ho wever, if the base pwm frequency is actively changed (by changing the top value), using the ocr1a as top is clearly a better choice due to its double buffer feature. in fast pwm mode, the compare units allow generation of pwm waveforms on the oc1x pins. setting the com1x1:0 bits to two will produce a inverted pwm and an non-inverted pwm output can be generated by setting the com1x1:0 to three (see table on page 131 ). the actual oc1x value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_oc1x). the pwm waveform is generated by setting (or clearing) the oc1x register at the compare match between ocr1x and tcnt1, and cl earing (or setting) the oc1x register at the timer cloc k cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocr1x register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr1x is set equal to bottom (0x0000) t he output will be a narrow spike for each top+1 timer clock cycle. setting the ocr1x equal to top will re sult in a constant high or low output (depending on the polarity of the output set by the com1x1:0 bits. 12345 tcntn (comnx1:0 = 2) ocnx ocnx period ocrnx/top update and tovn interrupt flag set and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 67 8 (comnx1:0 = 3) f ocnxpwm f clk_i/o n 1 top + () ? ---------------------------------- =
ata6614q [datasheet] 9240h?auto?10/14 126 a frequency (with 50% duty cycle) waveform ou tput in fast pwm mode ca n be achieved by setting oc1a to toggle its logical level on each compare match (com1a1:0 = 1). this applies onl y if ocr1a is used to define the top value (wgm13:0 = 15). the waveform generated will have a maximum frequency of f oc1a = f clk_i/o /2 when ocr1a is set to zero (0x0000). this feature is similar to the oc1a toggle in ctc mode, except the double buffer feature of th e output compare unit is enabled in the fast pwm mode. 5.15.9.4 phase correct pwm mode the phase correct pulse width modulation or phase correct pw m mode (wgm13:0 = 1, 2, 3, 10, or 11) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is, like the phase and frequency correct pwm mode, based on a dual-slope operation. the coun ter counts repeatedly from bo ttom (0x0000) to top and then from top to bottom. in non-inverting compare output m ode, the output compare (oc1x) is cleared on the compare match between tcnt1 and ocr1x while upcounting, and set on the compare match while downcoun ting. in inverting output compare mode, the operation is inverted . the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symme tric feature of the dual-slope pwm mode s, these modes are preferred for motor control applications. the pwm resolution for the phase correct pwm mode can be fixed to 8-, 9-, or 10-bit, or defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution in bits can be calculated by using the following equation: in phase correct pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgm13:0 = 1, 2, or 3), the value in icr1 (wgm13:0 = 10), or the value in ocr1a (wgm13:0 = 11). the counter has then reached the to p and changes the count direction. the tcnt1 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 5-45 . the figure shows phase correct pwm mode when ocr1a or icr1 is used to defi ne top. the tcnt1 value is in the timing diagram shown as a histogram for illustrating the dual-s lope operation. the diagram includes non-in verted and inverted pwm outputs. the small horizontal line marks on the tcnt1 slopes represen t compare matches between ocr1x and tcnt1. the oc1x interrupt flag will be set when a compare match occurs. figure 5-45. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov1) is set each time th e counter reaches bottom. when either ocr1a or icr1 is used for defining the top va lue, the oc1a or icf1 flag is set accord ingly at the same timer clock cycle as the ocr1x registers are updated with the double buffer value (at top). the interrupt flags can be used to generate an interrupt each time the counter reaches the top or bottom value. r pcpwm top 1 + () log 2 () log ---------------------------------- = 123 4 tcntn (comnx1:0 = 2) (comnx1:0 = 3) ocnx ocnx period tovn interrupt flag set (interrupt on bottom) ocrnx/top update and ocna interrupt flag set or icfn interrupt flag set (interrupt on top)
127 ata6614q [datasheet] 9240h?auto?10/14 when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcnt1 and the ocr1x. note that when using fixed top va lues, the unused bits are masked to zero when any of the ocr1x registers are written. as the third period shown in figure 5-45 illustrates, changing the top actively while the timer/counter is running in the phase correct mode can result in an unsymmetrical output. the reason for this can be found in the time of update of the ocr1x register. since the ocr1x update occurs at top, the pwm period starts and ends at top. this implies that the length of t he falling slope is determined by the previous top value, while t he length of the rising slope is determined by the new top value. when these two values differ the two slopes of the period will differ in length. the difference in length gives the unsy mmetrical result on the output. it is recommended to use the phase and frequency correct mode instead of the phase correct mode when changing the top value while the timer/counter is running. when using a static top value there ar e practically no differences between the two modes of operation. in phase correct pwm mode, the compare units allow gener ation of pwm waveforms on t he oc1x pins. setting the com1x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1x1:0 to three (see table on page 132 ). the actual oc1x value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_oc 1x). the pwm waveform is gen erated by setting (or clearing) the oc1x register at the compare match between ocr1x and tcnt1 when the counter incr ements, and clearing (or setting) the oc1x register at compare match between ocr1x and tcnt1 when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocr1x regist er represent special cases when generatin g a pwm waveform output in the phase correct pwm mode. if the ocr1x is set equal to bottom the out put will be continuously low and if set equal to top the output will be continuously high for no n-inverted pwm mode. for inverted pwm the output will have the opposite logic values. if ocr1a is used to define the top value (wgm13:0 = 11) and com1a1:0 = 1, the oc1a output will toggle with a 50% duty cycle. 5.15.9.5 phase and frequency correct pwm mode the phase and frequency correct pulse width modulation, or phase and frequency correct pwm mode (wgm13:0 = 8 or 9) provides a high resolution phase and frequency correct pwm waveform generation option. the phase and frequency correct pwm mode is, like the phase correct pwm mode, based on a dual-slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare outpu t mode, the output compare (oc1x) is cleared on the compare match between tcnt1 and ocr1x while upcounting, and set on the compare match while downcounting. in inverting compare output mode, the ope ration is inverted. the dual-slope operation gives a lower maximum operation frequency compared to the single-slope opera tion. however, due to the sym metric feature of the dual- slope pwm modes, these modes are pref erred for motor control applications. the main difference between the phase correct, and the ph ase and frequency correct pwm mode is the time the ocr1x register is updated by the oc r1x buffer register, (see figure 5-45 and figure 5-46 ). the pwm resolution for the phase and frequency correct pw m mode can be defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution in bits can be calculated using the following equation: in phase and frequency correct pwm mode the counter is incr emented until the counter value matches either the value in icr1 (wgm13:0 = 8), or the value in ocr1a (wgm13:0 = 9). the counter has then reached the top and changes the count direction. the tcnt1 value will be equal to top for o ne timer clock cycle. the timing diagram for the phase correct and frequency correct pwm mode is shown on figure 5-46 . the figure shows phase and frequency correct pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted a nd inverted pwm outputs. the small horizontal line marks on the tcnt1 slopes represent compare ma tches between ocr1x and tcnt1. the oc1x interrupt flag will be set when a compare match occurs. f ocnxpcpwm f clk_i/o 2 ntop ?? --------------------------- - = r pfcpwm top 1 + () log 2 () log ---------------------------------- =
ata6614q [datasheet] 9240h?auto?10/14 128 figure 5-46. phase and frequency correct pwm mode, timing diagram the timer/counter overflow fl ag (tov1) is set at the same timer clock cycl e as the ocr1x regist ers are updat ed with the double buffer value (at bottom). when either ocr1a or icr1 is used for defining the top value, the oc1a or icf1 flag set when tcnt1 has reached top. the interrupt flags can then be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcnt1 and the ocr1x. as figure 5-46 shows the output generated is, in c ontrast to the phase correct mode, symmetrical in all periods. since the ocr1x registers are updated at bottom, the length of the rising and the falling slopes will always be equal. this gives symmetrical output pulses and is therefore frequency correct. using the icr1 register for defining top works well when using fixed top values. by using icr1, the ocr1a register is free to be used for generating a pwm output on oc1a. ho wever, if the base pwm frequency is actively changed by changing the top value, using the ocr1a as top is clearly a better choice due to its double buffer feature. in phase and frequency correct pwm mode, the compare unit s allow generation of pwm waveforms on the oc1x pins. setting the com1x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1x1:0 to three (see table on page 132 ). the actual oc1x value will only be visible on the port pin if the data direction for the port pin is set as output (ddr_oc1x). the pwm waveform is generated by setting (or clearing) the oc1x register at the compare match between oc r1x and tcnt1 when the counter increment s, and clearing (or setting) the oc1x register at compare match be tween ocr1x and tcnt1 when the counter decr ements. the pwm frequency for the output when using phase and frequency correct pwm can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocr1x register represents spec ial cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr1x is set equal to bottom the out put will be continuously low and if set equal to top the output will be set to high for non-inverted pwm mode. for inve rted pwm the output will have the opposite logic values. if ocr1a is used to define the top value (wgm13:0 = 9) and co m1a1:0 = 1, the oc1a output will toggle with a 50% duty cycle. 1 2 34 tcntn (comnx1:0 = 2) (comnx1:0 = 3) ocnx ocnx period ocna interrupt flag set or icfn interrupt flag set (interrupt on top) ocrnx/ top update and tovn interrupt flag set (interrupt on bottom) f ocnxpfcpwm f clk_i/o 2 ntop ?? --------------------------- - =
129 ata6614q [datasheet] 9240h?auto?10/14 5.15.10 timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t1 ) is therefore shown as a clock enable signal in the following figures. the figures include information on when inte rrupt flags are set, and when the ocr1x register is updated with the ocr1x buffer value (only fo r modes utilizing double buffering). figure 5-47 shows a timing diagram for the setting of ocf1x. figure 5-47. timer/counter timing diagram, setting of ocf1x, no prescaling figure 5-48 shows the same timing data, but with the prescaler enabled. figure 5-48. timer/counter timing diagram, setting of ocf1x, with prescaler (f clk_i/o /8) ocrnx - 1 clk i/o (clk i/o /1) tcntn ocrnx ocfnx clk tn ocrnx ocrnx value ocrnx + 1 ocrnx + 2 ocrnx - 1 clk i/o (clk i/o /8) tcntn ocrnx ocfnx clk tn ocrnx ocrnx + 1 ocrnx value ocrnx + 2
ata6614q [datasheet] 9240h?auto?10/14 130 figure 5-49 shows the count sequence close to top in various modes. when using phase and frequency correct pwm mode the ocr1x register is updated at bottom. the timing diagrams will be the sa me, but top should be replaced by bottom, top-1 by bottom+1 and so on. the same renamin g applies for modes that set the tov1 flag at bottom. figure 5-49. timer/counter timing diagram, no prescaling figure 5-50 shows the same timing data, but with the prescaler enabled. figure 5-50. timer/counter timi ng diagram, with prescaler (f clk_i/o /8) top - 1 clk i/o (clk i/o /1) tcntn (ctc and fpwm) ocrnx (update at top) tcntn (pc and pfc pwm) tovn (fpwm) and icfn (if used as top) clk tn top old ocrnx value new ocrnx value bottom bottom + 1 top - 1 top top - 1 top - 2 top - 1 top bottom bottom + 1 top - 1 top top - 1 top - 2 clk i/o (clk i/o /8) tcntn (ctc and fpwm) ocrnx (update at top) tcntn (pc and pfc pwm) tovn (fpwm) and icfn (if used as top) clk tn old ocrnx value new ocrnx value
131 ata6614q [datasheet] 9240h?auto?10/14 5.15.11 register description 5.15.11.1 tccr1a ? timer/counter1 control register a ? bit 7:6 ? com1a1:0: compare output mode for channel a ? bit 5:4 ? com1b1:0: compare output mode for channel b the com1a1:0 and com1b1:0 control the output compare pins (oc1a and oc1b respectively) behavior. if one or both of the com1a1:0 bits are written to one, the oc1a output overri des the normal port functionality of the i/o pin it is connected to. if one or both of the com1b1:0 bit are written to one, th e oc1b output overrides the norma l port functionality of the i/o pin it is connected to. however, note that the data direction register (ddr) bit corresponding to the oc1a or oc1b pin must be set in order to enable the output driver. when the oc1a or oc1b is connected to the pin, the functi on of the com1x1:0 bits is dependent of the wgm13:0 bits setting. table 5-50 shows the com1x1:0 bit functionality when the wgm13: 0 bits are set to a normal or a ctc mode (non- pwm). table 5-51 shows the com1x1:0 bit functionality when th e wgm13:0 bits are set to the fast pwm mode. note: 1. a special case occurs when ocr1a/ocr1b equals top and com1a1/com1b1 is set. in this case the com- pare match is ignored, but the set or clear is done at bottom. see section 5.15.9.3 ?fast pwm mode? on page 124 for more details. bit 76543210 (0x80) com1a1 com1a0 com1b1 com1b0 ? ? wgm11 wgm10 tccr1a read/write r/w r/w r/w r/w r r r/w r/w initial value00000000 table 5-50. compare output mode, non-pwm com1a1/com1b1 com1a0/com1b0 description 0 0 normal port operation, oc1a/oc1b disconnected. 0 1 toggle oc1a/oc1b on compare match. 1 0 clear oc1a/oc1b on compare matc h (set output to low level). 1 1 set oc1a/oc1b on compare match (set output to high level). table 5-51. compare output mode, fast pwm (1) com1a1/com1b1 com1a0/com1b0 description 0 0 normal port operation, oc1a/oc1b disconnected. 0 1 wgm13:0 = 14 or 15: toggle oc1a on compare match, oc1b disconnected (normal port operation). for all other wgm1 settings, normal port operation, oc1a/oc1b disconnected. 1 0 clear oc1a/oc1b on compare match, set oc1a/oc1b at bottom (non-inverting mode) 1 1 set oc1a/oc1b on compare match, clear oc1a/oc1b at bottom (inverting mode)
ata6614q [datasheet] 9240h?auto?10/14 132 table 5-52 shows the com1x1:0 bit functionality when the wgm13: 0 bits are set to the phase correct or the phase and frequency correct, pwm mode. note: 1. a special case occurs when ocr1a/ocr1b equals top and com1a1/com1b1 is set. see section 5.15.9.4 ?phase correct pwm mode? on page 126 for more details. ? bit 1:0 ? wgm11:0: wa veform gene ration mode combined with the wgm13:2 bits found in the tccr1b register, t hese bits control the counting sequence of the counter, the source for maximum (top) counter value, and w hat type of waveform generation to be used, see table 5-53 . modes of operation supported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and three types of pulse width modulation (pwm) modes (see section 5.15.9 ?modes of operation? on page 123 ). note: 1. the ctc1 and pwm11:0 bit definition names are obsolete. use the wgm 12:0 definitions. however, the functionality and location of these bits are compatible with previous versions of the timer. table 5-52. compare output mode, phase correct and phase and frequency correct pwm (1) com1a1/com1b1 com1a0/com1b0 description 0 0 normal port operation, oc1a/oc1b disconnected. 0 1 wgm13:0 = 9 or 11: toggle oc1a on compare match, oc1b disconnected (normal port operation). for all other wgm1 settings, normal port operat ion, oc1a/oc1b disconnected. 1 0 clear oc1a/oc1b on compare match when up-counting. set oc1a/oc1b on compare match when downcounting. 1 1 set oc1a/oc1b on compare match when up-counting. clear oc1a/oc1b on compare match when downcounting. table 5-53. waveform generati on mode bit description (1) mode wgm13 wgm12 (ctc1) wgm11 (pwm11) wgm10 (pwm10) timer/counter mode of operation top update of ocr1 x at tov1 flag set on 0 0 0 0 0 normal 0xffff immediate max 1 0 0 0 1 pwm, phase correct, 8-bit 0x00ff top bottom 2 0 0 1 0 pwm, phase correct, 9-bit 0x01ff top bottom 3 0 0 1 1 pwm, phase correct, 10-bit 0x03ff top bottom 4 0 1 0 0 ctc ocr1a immediate max 5 0 1 0 1 fast pwm, 8-bit 0x00ff bottom top 6 0 1 1 0 fast pwm, 9-bit 0x01ff bottom top 7 0 1 1 1 fast pwm, 10-bit 0x03ff bottom top 8 1 0 0 0 pwm, phase and frequency correct icr1 bottom bottom 9 1 0 0 1 pwm, phase and frequency correct ocr1a bottom bottom 10 1 0 1 0 pwm, phase correct icr1 top bottom 11 1 0 1 1 pwm, phase correct ocr1a top bottom 12 1 1 0 0 ctc icr1 immediate max 13 1 1 0 1 (reserved) ? ? ? 14 1 1 1 0 fast pwm icr1 bottom top 15 1 1 1 1 fast pwm ocr1a bottom top
133 ata6614q [datasheet] 9240h?auto?10/14 5.15.11.2 tccr1b ? timer/counter1 control register b ? bit 7 ? icnc1: input capture noise canceler setting this bit (to one) activates the input capture noise cancel er. when the noise canceler is activated, the input from the input capture pin (icp1) is filtered. the filter function requires four successive equal valued samples of the icp1 pin for changing its output. the input capture is therefore delayed by four oscillator cycles when the noise canceler is enabled. ? bit 6 ? ices1: input capture edge select this bit selects which edge on the input capture pin (icp1) t hat is used to trigger a capture event. when the ices1 bit is written to zero, a falling (negative) edge is used as trigger, and when the ices1 bit is written to one, a rising (positive) ed ge will trigger the capture. when a capture is triggered according to the ices1 setting, the counter value is copied into the input capture register (icr1). the event will also set the input ca pture flag (icf1), and this can be used to cause an input capture interrupt, if thi s interrupt is enabled. when the icr1 is used as top value (see description of the wgm13:0 bits located in the tccr1a and the tccr1b register), the icp1 is disconnected and consequ ently the input capture function is disabled. ? bit 5 ? reserved bit this bit is reserved for future use. for ensuring compatibilit y with future devices, this bit must be written to zero when tccr1b is written. ? bit 4:3 ? wgm13:2: wa veform gene ration mode see tccr1a register description. ? bit 2:0 ? cs12:0: clock select the three clock sele ct bits select the clock source to be used by the timer/counter, see figure 5-47 and figure 5-48 . if external pin modes are used for the timer/counter1, transit ions on the t1 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. bit 7654 3210 (0x81) icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 tccr1b read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 5-54. clock select bit description cs12 cs11 cs10 description 0 0 0 no clock source (timer/counter stopped). 0 0 1 clk i/o /1 (no prescaling) 0 1 0 clk i/o /8 (from prescaler) 0 1 1 clk i/o /64 (from prescaler) 1 0 0 clk i/o /256 (from prescaler) 1 0 1 clk i/o /1024 (from prescaler) 1 1 0 external clock source on t1 pin. clock on falling edge. 1 1 1 external clock source on t1 pin. clock on rising edge.
ata6614q [datasheet] 9240h?auto?10/14 134 5.15.11.3 tccr1c ? timer/counter1 control register c ? bit 7 ? foc1a: force output compare for channel a ? bit 6 ? foc1b: force output compare for channel b the foc1a/foc1b bits are only active when the wgm13:0 bits specifies a non-pwm mode. when writing a logical one to the foc1a/foc1b bit, an immediate comp are match is forced on the waveform ge neration unit. the oc1a/oc1b output is changed according to its com1x1:0 bits setting. note that th e foc1a/foc1b bits are implemen ted as strobes. therefore it is the value present in the co m1x1:0 bits that determine the effect of the forced compare. a foc1a/foc1b strobe will not generate any interrupt nor will it clear the timer in clear timer on compare match (ctc) mode using ocr1a as top. the foc1a/foc1b bits are always read as zero. 5.15.11.4 tcnt1h and tcnt1l ? timer/counter1 the two timer/counter i/o locations (tcnt1h and tcnt1l, combi ned tcnt1) give direct access, both for read and for write operations, to the timer/counter unit 16-bit counter. to ensure that both th e high and low bytes are read and written simultaneously when the cpu accesses thes e registers, the access is performed usi ng an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-b it registers (see section 5.15.3 ?accessi ng 16-bit registers? on page 115 ). modifying the counter (tcnt1) while the counter is running introduces a risk of missing a compare match between tcnt1 and one of the ocr1x registers. writing to the tcnt1 register blocks (removes) the compare match on the follo wing timer clock for all compare units. 5.15.11.5 ocr1ah and ocr1al ? output compare register 1 a 5.15.11.6 ocr1bh and ocr1bl ? output compare register 1 b the output compare registers c ontain a 16-bit value that is continuously co mpared with the counter value (tcnt1). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc1x pin. the output compare registers are 16-bit in size. to ensure that both the high and low bytes are written simultaneously when the cpu writes to these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by al l the other 16-bit registers (see section 5.15.3 ?accessing 16-bi t registers? on page 115 ). bit 7654 3210 (0x82) foc1a foc1b ? ? ? ? ? ? tccr1c read/write r/w r/w r r r r r r initial value0000 0000 bit 76543210 (0x85) tcnt1[15:8] tcnt1h (0x84) tcnt1[7:0] tcnt1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x89) ocr1a[15:8] ocr1ah (0x88) ocr1a[7:0] ocr1al read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x8b) ocr1b[15:8] ocr1bh (0x8a) ocr1b[7:0] ocr1bl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
135 ata6614q [datasheet] 9240h?auto?10/14 5.15.11.7 icr1h and icr1l ? input capture register 1 the input capture is updated with the counter (tcnt1) value each time an event occurs on the icp1 pin (or optionally on the analog comparator output for timer/co unter1). the input capture can be used for defining the counter top value. the input capture register is 16-bit in size. to ensure that both the high and lo w bytes are read simultaneously when the cpu accesses these registers, th e access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all th e other 16-bit registers (see section 5.15.3 ?accessing 16-bit registers? on page 115 ). 5.15.11.8 timsk1 ? timer/counte r1 interrupt mask register ? bit 7, 6 ? res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 5 ? icie1: timer/counter1 , input capture interrupt enable when this bit is written to one, and the i-flag in the status register is set (i nterrupts globally enabled), the timer/counter1 input capture interrupt is enabled. the corresponding interrupt vector (see section 5.11 ?interrupts? on page 73 ) is executed when the icf1 flag, loca ted in tifr1, is set. ? bit 4, 3 ? res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 2 ? ocie1b: timer/counter1, outp ut compare b match interrupt enable when this bit is written to one, and the i-flag in the status register is set (i nterrupts globally enabled), the timer/counter1 output compare b match interrupt is enabl ed. the corresponding interrupt vector (see section 5.11 ?interrupts? on page 73 ) is executed when the ocf1b flag, located in tifr1, is set. ? bit 1 ? ocie1a: timer/counter1, outp ut compare a match interrupt enable when this bit is written to one, and the i-flag in the status register is set (i nterrupts globally enabled), the timer/counter1 output compare a match interrupt is enabled. the corresponding interrupt vector (see section 5.11 ?interrupts? on page 73 ) is executed when the ocf1a flag, located in tifr1, is set. ? bit 0 ? toie1: timer/counter1, overflow interrupt enable when this bit is written to one, and the i-flag in the status register is set (i nterrupts globally enabled), the timer/counter1 overflow interrupt is enabled. the corresponding interrupt vector (see section 5.11 ?interrupts? on page 73 ) is executed when the tov1 flag, locat ed in tifr1, is set. bit 76543210 (0x87) icr1[15:8] icr1h (0x86) icr1[7:0] icr1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x6f) ? ? icie1 ? ? ocie1b ocie1a toie1 timsk1 read/write r r r/w r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0
ata6614q [datasheet] 9240h?auto?10/14 136 5.15.11.9 tifr1 ? timer/counte r1 interrupt flag register ? bit 7, 6 ? res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 5 ? icf1: timer/counter1, input capture flag this flag is set when a capture event oc curs on the icp1 pin. when the input capt ure register (icr1) is set by the wgm13:0 to be used as the top value, the icf1 flag is set when the counter reaches the top value. icf1 is automatically cleared when the input capture interrupt vector is executed. alternatively, icf1 can be cleared by writing a logic one to its bit location. ? bit 4, 3 ? res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 2 ? ocf1b: timer/counter1 , output compare b match flag this flag is set in the timer clock cycl e after the counter (tcnt1) value matches the output compare register b (ocr1b). note that a forced output compare (foc 1b) strobe will not set the ocf1b flag. ocf1b is automatically cleared when the output compare match b interrupt vector is executed. alternatively, ocf1b can be cleared by writing a logic one to its bit location. ? bit 1 ? ocf1a: timer/counter1 , output compare a match flag this flag is set in the timer clock cycl e after the counter (tcnt1) value matches the output compare register a (ocr1a). note that a forced output compare (foc 1a) strobe will not set the ocf1a flag. ocf1a is automatically cleared when the ou tput compare match a interrupt vector is executed. alternatively, ocf1a can be cleared by writing a logic one to its bit location. ? bit 0 ? tov1: timer/counter1, overflow flag the setting of this flag is dependent of the wgm13:0 bits setting. in normal and ctc modes, the tov1 flag is set when the timer overflows. refer to table 5-53 on page 132 for the tov1 flag behavior when using another wgm13:0 bit setting. tov1 is automatically cleared when the ti mer/counter1 overflow inte rrupt vector is executed. alternatively, tov1 can be cleared by writing a logic one to its bit location. bit 76543210 0x16 (0x36) ? ? icf1 ? ? ocf1b ocf1a tov1 tifr1 read/write r r r/w r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0
137 ata6614q [datasheet] 9240h?auto?10/14 5.16 timer/counter0 and timer/counter1 prescalers section 5.14 ?8-bit timer/counter0 with pwm? on page 98 and section 5.15 ?16-bit timer/counter1 with pwm? on page 113 share the same prescaler module, but the timer/counters ca n have different prescaler settings. the description below applies to both timer/coun ter1 and timer/counter0. 5.16.1 internal clock source the timer/counter can be clock ed directly by the system clock (by setting th e csn2:0 = 1). this provides the fastest operation, with a maximum timer/counter clock frequency equal to system clock frequency (f clk_i/o ). alternatively, one of four taps from the prescaler can be used as a clock source. the prescaled clock has a frequency of either f clk_i/o /8, f clk_i/o /64, f clk_i/o /256, or f clk_i/o /1024. 5.16.2 prescaler reset the prescaler is free running, i.e., operates independently of the clock select logic of the timer/counter, and it is shared by timer/counter1 and timer/counter0. since the prescaler is not af fected by the timer/counter?s clock select, the state of the prescaler will have implications for situations where a prescale d clock is used. one example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler (6 > csn2:0 > 1). the num ber of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to n+1 system clock cycles, where n equals the prescaler divisor (8, 64, 256, or 1024). it is possible to use the prescaler reset for synchronizing t he timer/counter to program exec ution. however, care must be taken if the other timer/counte r that shares the same prescaler also uses prescaling. a prescaler reset will affect the prescaler period for all timer/counters it is connected to. 5.16.3 external clock source an external clock source applied to the t1/t0 pin can be used as timer/counter clock (clk t1 /clk t0 ). the t1/t0 pin is sampled once every system clock cycle by the pin syn chronization logic. the synchronized (sampled) sign al is then passed through the edge detector. figure 5-51 shows a functional equivalent block diagram of the t1/t0 synchronization and edge detector logic. the registers are clocked at the pos itive edge of the inte rnal system clock (clk i/o ). the latch is transparent in the high period of t he internal system clock. the edge detector generates one clk t1 /clk t0 pulse for each positive (csn2:0 = 7) or negative (csn2:0 = 6) edge it detects. figure 5-51. t1/t0 pin sampling the synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles from an edge has been applied to the t1/t0 pin to the counter is updated. enabling and disabling of the clock input must be done when t1/t0 has been stable for at least one system clock cycle, otherwise it is a risk that a false timer/counter clock pulse is generated. each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling. the external clock must be guaranteed to have less than half the system clock frequency (f extclk < f clk_i/o /2) given a 50/50% duty cycle. since the edge detector uses sampling, the maximum frequen cy of an external clock it can detect is half the sampling frequency (nyquist sampling theorem). however, due to variat ion of the system clock frequency and duty cycle caused by oscillator source (crystal, resonator, and capacitors) toler ances, it is recommended that ma ximum frequency of an external clock source is less than f clk_i/o /2.5. an external clock source can not be prescaled. tn synchronization edge detector tn_sync (to clock select logic) q le d q d q d clk i/o
ata6614q [datasheet] 9240h?auto?10/14 138 figure 5-52. prescaler for ti mer/counter0 and timer/counter1 (1) note: 1. the synchronization logic on the input pins ( t1/t0) is shown in figure 5-51 on page 137 . 5.16.4 register description 5.16.4.1 gtccr ? general time r/counter control register ? bit 7 ? tsm: timer/counter synchronization mode writing the tsm bit to one activates the timer/counter synchroniza tion mode. in this mode, the va lue that is written to the psrasy and psrsync bits is kept, hence keeping the corresponding prescaler reset signals asserted. this ensures that the corresponding timer/counters are halted and can be conf igured to the same value without the risk of one of them advancing during configuration. when the tsm bit is written to zero, the psrasy and psrsync bits are cleared by hardware, and the time r/counters start counting simultaneously. ? bit 0 ? psrsync: prescaler reset when this bit is one, timer/counter1 and timer/counter0 presca ler will be reset. this bit is normally cleared immediately by hardware, except if the tsm bit is set. note that timer/count er1 and timer/counter0 share the same prescaler and a reset of this prescaler will affect both timers. timer/counter1 clock source clk t1 clk i/o psrsync t0 10-bit t/c prescaler 0 cs10 ck/8 ck/64 ck/256 ck/1024 cs11 cs12 synchronization clear t1 synchronization timer/counter0 clock source clk t0 0 cs00 cs01 cs02 bit 765432 1 0 0x23 (0x43) tsm ? ? ? ? ? psrasy psrsync gtccr read/writer/wrrrrrr/wr/w initial value000000 0 0
139 ata6614q [datasheet] 9240h?auto?10/14 5.17 8-bit timer/counter2 with pwm and asynchronous operation 5.17.1 features single channel counter clear timer on compare match (auto reload) glitch-free, phase correct pulse width modulator (pwm) frequency generator 10-bit clock prescaler overflow and compare match interrupt sources (tov2, ocf2a and ocf2b) allows clocking from external 32khz watc h crystal independent of the i/o clock 5.17.2 overview timer/counter2 is a general purpose, single channel, 8-bit ti mer/counter module. a simplified block diagram of the 8-bit timer/counter is shown in figure 5-53 . the device-specific i/o register and bit locations are listed in section 5.17.11 ?register description? on page 150 . the prtim2 bit in section 5.9.10 ?minimizing power consumption? on page 60 must be written to zero to enable timer/counter2 module. figure 5-53. 8-bit timer/counter block diagram tcntn timer/counter count clear direction ocrna ocrnb tccrna tccrnb = top bottom ocna (int. req.) waveform generation fixed top value data bus = = = 0 ocna ocnb (int. req.) waveform generation ocnb control logic clk tn tovn (int. req.) edge detector (from prescaler) clock select tn
ata6614q [datasheet] 9240h?auto?10/14 140 5.17.2.1 registers the timer/counter (tcnt2) and output compare register (o cr2a and ocr2b) are 8-bit registers. interrupt request (shorten as int.req.) signals are all visible in the timer interr upt flag register (tifr2). all interrupts are individually mas ked with the timer interrupt mask register (timsk2). tifr2 and timsk2 are not shown in the figure. the timer/counter can be clocked internally, via the prescale r, or asynchronously clocked from the tosc1/2 pins, as detailed later in this section. the asynchronous operation is controlled by the asynchronous status register (assr). the clock select logic block contro ls which clock source he timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no clock source is selected. the out put from the clock select logic is referred to as the timer clock (clk t2 ). the double buffered output compare regist er (ocr2a and ocr2b) are compared with the timer/counter value at all times. the result of the compare can be used by the waveform gene rator to generate a pwm or variable frequency output on the output compare pins (oc2a and oc2b). see section 5.17.5 ?output compare unit? on page 141 for details. the compare match event will also set the compare flag (ocf2a or ocf2b) which can be used to generate an output compare interrupt request. 5.17.2.2 definitions many register and bit references in this document are written in general form. a lower case ?n? replaces the timer/counter number, in this case 2. however, when using the register or bit defines in a pr ogram, the precise form must be used, i.e., tcnt2 for accessing timer/counter2 counter value and so on. the definitions in table 5-55 are also used extensively throughout the section. 5.17.3 timer/counter clock sources the timer/counter can be clocked by an internal synchronous or an external asynchronous clock source. the clock source clk t2 is by default equal to the mcu clock, clk i/o . when the as2 bit in the assr register is written to logic one, the clock source is taken from the timer/counter oscillator connected to tosc1 and tosc2. for details on asynchronous operation, see section 5.17.11.8 ?assr ? asynchronous status register? on page 155 . for details on clock sources and prescaler, see section 5.17.10 ?timer/counter prescaler? on page 150 . 5.17.4 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 5-54 on page 140 shows a block diagram of the counter and its surrounding environment. figure 5-54. counter unit block diagram table 5-55. definitions case definition bottom the counter reaches the bottom when it becomes zero (0x00). max the counter reaches its maximum when it becomes 0xff (decimal 255). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr2a register. the assignment is dependent on the mode of operation. top bottom tovn (int. req.) data bus control logic tcntn clk tn clear count direction clk i/o prescaler t/c oscillator tosc1 tosc2
141 ata6614q [datasheet] 9240h?auto?10/14 signal description (internal signals): count increment or decrement tcnt2 by 1. direction selects between increment and decrement. clear clear tcnt2 (set all bits to zero). clk tn timer/counter clock, referred to as clk t2 in the following. top signalizes that tcnt2 has reached maximum value. bottom signalizes that tcnt2 has reached minimum value (zero). depending on the mode of operation used, t he counter is cleared, incremented, or decremented at each timer clock (clk t2 ). clk t2 can be generated from an external or internal clock source , selected by the clock select bits (cs22:0). when no clock source is selected (cs22:0 = 0) the time r is stopped. however, the tcnt2 value can be accessed by the cpu, regardless of whether clk t2 is present or not. a cpu write overrides (has pr iority over) all counter clear or count operations. the counting sequence is determined by the setting of the wgm21 and wgm20 bits located in the timer/counter control register (tccr2a) and the wgm22 located in the timer/counter contro l register b (tccr2b). th ere are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare outputs oc2a and oc2b. for more details about advanced counting sequences and waveform generation, see section 5.17.7 ?modes of operation? on page 143 . the timer/counter overflow flag (tov2) is set according to t he mode of operation selected by the wgm22:0 bits. tov2 can be used for generating a cpu interrupt. 5.17.5 output compare unit the 8-bit comparator continuously com pares tcnt2 with the output compare register (ocr2a and ocr2b). whenever tcnt2 equals ocr2a or ocr2b, the comparator signals a ma tch. a match will set the outpu t compare flag (ocf2a or ocf2b) at the next timer clo ck cycle. if the corresponding interrupt is enabled , the output compare fl ag generates an output compare interrupt. the output compare flag is automatically cleared when the interrupt is execut ed. alternatively, the output compare flag can be cleared by software by writing a logical one to its i/o bit location. the waveform generator uses the match signal to generate an output according to operatin g mode set by the wgm22:0 bits and compare output mode (com2x1:0) bits. the max and bottom signals are used by t he waveform generator for handling the special cases of the extreme values in some modes of operation (see section 5.17.7 ?modes of operation? on page 143 ). figure 5-55 shows a block diagram of the output compare unit. figure 5-55. output comp are unit, block diagram ocfnx (int. req.) = (8-bit comparator) ocrnx waveform generator tcntn ocnx top bottom focn wgmn[1:0] comnx[1:0] data bus
ata6614q [datasheet] 9240h?auto?10/14 142 the ocr2x register is double buffered when using any of the pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the doubl e buffering is disabled. the double buffering synchronizes the update of the ocr2x compare register to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr2x register access may seem co mplex, but this is not case. when th e double buffering is enabled, the cpu has access to the ocr2x buffer register, and if double buffer ing is disabled the cpu will access the ocr2x directly. 5.17.5.1 force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (foc2x) bit. forc ing compare match will not set the ocf2x flag or reload/clear the timer, but the oc2x pin will be updated as if a real compare match had occurred (the co m2x1:0 bits settings define w hether the oc2x pin is set, cleared or toggled). 5.17.5.2 compare match blocking by tcnt2 write all cpu write operations to the tcnt2 register will block any co mpare match that occurs in th e next timer clock cycle, even when the timer is stopped. this feature allows ocr2x to be initialized to the same value as tcnt2 without triggering an interrupt when the timer/counter clock is enabled. 5.17.5.3 using the ou tput compare unit since writing tcnt2 in any mode of ope ration will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt2 when using the output compar e channel, independently of w hether the timer/counter is running or not. if the value written to tcnt2 equals the ocr2 x value, the compare match will be missed, resulting in incorrect waveform generation. similarly, do not write th e tcnt2 value equal to bottom when the counter is downcounting. the setup of the oc2x should be performed befo re setting the data direction register for the port pin to output. the easiest way of setting the oc2x value is to us e the force output compare (foc2x) strobe bit in normal mode. the oc2x register keeps its value even when changing between waveform generation modes. be aware that the com2x1:0 bits are not double buffered together with the compar e value. changing the com2x1:0 bits will take effect immediately. 5.17.6 compare match output unit the compare output mode (com2x1:0) bits have two functi ons. the waveform generator uses the com2x1:0 bits for defining the output compare (oc2x) state at the next compare match. also, the com2x1:0 bits control the oc2x pin output source. figure 5-56 shows a simplified schematic of the logic affected by the com2x1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only th e parts of the general i/o port control registers (ddr and port) that are affected by the com2x1:0 bits ar e shown. when referring to the oc2x state, the reference is for the internal oc2x register, not the oc2x pin.
143 ata6614q [datasheet] 9240h?auto?10/14 figure 5-56. compare match output unit, schematic the general i/o port function is overridden by the output co mpare (oc2x) from the waveform generator if either of the com2x1:0 bits are set. however, the oc2x pin direction (input or output) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the oc2x pin (ddr_oc 2x) must be set as output before the oc2x value is visible on the pin. the port override func tion is independent of the waveform generation mode. the design of the output compare pin logic allows initialization of the oc2x state before the output is enabled. note that some com2x1:0 bit settings are reserved for certain modes of operation (see section 5.17.11 ?register description? on page 150 ). 5.17.6.1 compare output mode and waveform generation the waveform generator uses the com2x1:0 bits differentl y in normal, ctc, and pwm modes. for all modes, setting the com2x1:0 = 0 tells the waveform generator that no action on the oc2x register is to be performed on the next compare match. for compare output actions in the non-pwm modes refer to table 5-59 on page 151 . for fast pwm mode, refer to table 5-60 on page 152 , and for phase correct pwm refer to table 5-61 on page 152 . a change of the com2x1:0 bits state will have effect at the first compare match after the bi ts are written. for non-pwm modes, the action can be forced to have immedi ate effect by using the foc2x strobe bits. 5.17.7 modes of operation the mode of operation, i.e., t he behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm22:0) and compare output mode (com2x1:0) bits. the compare output mode bits do not affect the counting sequence, while t he waveform generation mode bits do. the com2x1:0 bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non-p wm modes the com2x1:0 bits control whether the output should be set, cleared, or toggled at a compare match (see section 5.17.6 ?compare match output unit? on page 142 ). for detailed timing information refer to section 5.17.8 ?timer/counter timing diagrams? on page 147 . data bus 0 1 q d comnx1 comnx0 focnx ocnx waveform generator q d port q d ddr ocnx pin clk i/o
ata6614q [datasheet] 9240h?auto?10/14 144 5.17.7.1 normal mode the simplest mode of operation is t he normal mode (wgm22:0 = 0). in this mo de the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bottom (0x00). in no rmal operation the timer/counter overflow flag (tov2) will be set in the same timer cl ock cycle as the tcnt2 becomes zero . the tov2 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov2 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. 5.17.7.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm22:0 = 2), the ocr2 a register is used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcnt2) matches the ocr2a. the ocr2a defines the top value for the counter, hence also its resolution. this mode allo ws greater control of the comp are match output frequency. it also simplifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 5-57 . the counter value (tcnt2) increases until a compare match occurs between tcnt2 and ocr2a, and then counter (tcnt2) is cleared. figure 5-57. ctc mode, timing diagram an interrupt can be generated each time the counter value reac hes the top value by using the ocf2a flag. if the interrupt is enabled, the interrupt handler routine can be used for updat ing the top value. however, changing top to a value close to bottom when the counter is running with non e or a low prescaler value must be done with care since the ctc mode does not have the double buffering feat ure. if the new value written to ocr2a is lower than the current value of tcnt2, the counter will miss the compare match. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc2a output can be set to to ggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com2a1:0 = 1). the oc2a value will not be visible on the port pin unless the data direction for the pin is set to out put. the waveform generated will have a maximum frequency of f oc2a = f clk_i/o /2 when ocr2a is set to zero (0x00). the wave form frequency is defined by the following equation: the n variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). as for the normal mode of operat ion, the tov2 flag is se t in the same timer clock cycle that the counter counts from max to 0x00. 12 tcntn (comnx[1:0] = 1) ocnx (toggle) period 3 ocnx interrupt flag set 4 f ocnx f clk_i/o 2 n 1 ocrnx + () ?? ------------------------------------------------ - =
145 ata6614q [datasheet] 9240h?auto?10/14 5.17.7.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgm22: 0 = 3 or 7) provides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm optio n by its single-slope operation. the counter counts from bottom to top then restarts from bottom. top is defined as 0xff when wgm2:0 = 3, and ocr2a when mgm2:0 = 7. in non-inverting compare output mode, the output compare (oc2x) is cleared on the compare match between tcnt2 and ocr2x, and set at bottom. in inverting compare output mode, the output is set on compare match and cleared at bottom. due to the single-slope operatio n, the operating frequency of the fast pwm mode can be twice as high as the phase correct pwm mode that uses dual-s lope operation. this high frequency make s the fast pwm mode well suited for power regulation, rectification, and dac applications. high frequency allows physically small sized external components (coils, capacitors), and theref ore reduces total system cost. in fast pwm mode, the counter is incremen ted until the counter value ma tches the top value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 5-58 . the tcnt2 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the sm all horizontal line marks on the tcnt2 slopes represent compare matches between ocr2x and tcnt2. figure 5-58. fast pwm mode, timing diagram the timer/counter overflow flag (tov2) is set each time the co unter reaches top. if the inte rrupt is enabled, the interrupt handler routine can be used fo r updating the compare value. in fast pwm mode, the compare unit allo ws generation of pwm waveforms on the oc2x pin. setting the com2x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com2x1:0 to three. top is defined as 0xff when wgm2:0 = 3, and ocr2a when mgm2:0 = 7. (see table 5-57 on page 151 ). the actual oc2x value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generat ed by setting (or clearing) the oc2x register at the compare match between ocr2x and tcnt2, and clearing (or setting) the oc2x register at the timer cl ock cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescale fact or (1, 8, 32, 64, 128, 256, or 1024). the extreme values for the ocr2a register represent specia l cases when generating a pwm waveform output in the fast pwm mode. if the ocr2a is set equal to bottom, the output will be a narrow sp ike for each max+1 timer clock cycle. setting the ocr2a equal to max will result in a constantly high or low output (depending on the pol arity of the output set by the com2a1:0 bits). 1234567 tcntn (comnx1:0 = 2) (comnx1:0 = 3) ocnx ocnx period ocrnx update and tovn interrupt flag set ocrnx interrupt flag set f ocnxpwm f clk_i/o n 256 ? ----------------- =
ata6614q [datasheet] 9240h?auto?10/14 146 a frequency (with 50% duty cycle) waveform output in fast pw m mode can be achieved by settin g oc2x to togg le its logical level on each compare match (com2x1:0 = 1). the waveform generated will have a maximum frequency of f oc2 = f clk_i/o /2 when ocr2a is set to zero. this feature is similar to the oc 2a toggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast pwm mode. 5.17.7.4 phase correct pwm mode the phase correct pwm mode (wgm22:0 = 1 or 5) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual-slope operation. the counter count s repeatedly from bottom to top and then from top to bottom. top is defined as 0xff when wgm2:0 = 3, and ocr2a when mgm2:0 = 7. in non- inverting compare output mode, the output compare (oc2x) is cleared on the compare match between tcnt2 and ocr2x while upcounting, and set on the compare match while downcount ing. in inverting output co mpare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmetric feature of the dual-slope pwm modes, t hese modes are preferred for motor control applications. in phase correct pwm mode the counter is incremented until the counter value matches top. when the counter reaches top, it changes the count direct ion. the tcnt2 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 5-59 . the tcnt2 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non- inverted and inverted pwm outputs. the small horizontal line marks on the tcnt2 slopes represent compare matches between ocr2x and tcnt2. figure 5-59. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov2) is set each time the counter reaches bottom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct pwm mode, the compare unit allows ge neration of pwm waveforms on the oc2x pin. setting the com2x1:0 bits to two will produce a non-inverted pwm. an inverted pwm output can be generated by setting the com2x1:0 to three. top is defined as 0xff when wgm2:0 = 3, and ocr2a when mgm2:0 = 7 (see table 5-58 on page 151 ). the actual oc2x value will only be visible on the port pin if the data direction fo r the port pin is se t as output. the pwm waveform is generated by clearing (or setting) the oc2x re gister at the compare match between ocr2x and tcnt2 when the counter increments, and setting (or clearing) the oc2x register at compare match between ocr2x and tcnt2 when the counter decrements. the pwm frequency for the output when us ing phase correct pwm can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 32, 64, 128, 256, or 1024). 123 tcntn (comnx1:0 = 2) (comnx1:0 = 3) ocnx ocnx period tovn interrupt flag set ocrnx update ocnx interrupt flag set f ocnxpcpwm f clk_i/o n 510 ? ----------------- =
147 ata6614q [datasheet] 9240h?auto?10/14 the extreme values for the ocr2a regist er represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr2a is set equal to bottom, the output will be continuously low and if set equal to max the output will be continuously high for no n-inverted pwm mode. for inverted pwm the output will have the opposite logic values. at the very start of period 2 in figure 5-59 ocnx has a transition from high to lo w even though there is no compare match. the point of this transition is to gua rantee symmetry around bottom. there are tw o cases that give a transition without compare match. ocr2a changes its value from max, like in figure 5-59 . when the ocr2a value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocn value at max must correspond to the result of an up-counting compare match. the timer starts counting from a value higher than the on e in ocr2a, and for that reason misses the compare match and hence the ocn change that would have happened on the way up. 5.17.8 timer/counter timing diagrams the following figures show the timer/counter in synchronous mode, and the timer clock (clk t2 ) is therefore shown as a clock enable signal. in asynchronous mode, clk i/o should be replaced by the timer/counter oscillator clock. the figures include information on when interrupt flags are set. figure 5-60 contains timing data for basic ti mer/counter operation. the figure shows the count sequence close to the max value in all modes other than phase correct pwm mode. figure 5-60. timer/counter timing diagram, no prescaling figure 5-61 shows the same timing data, but with the prescaler enabled. figure 5-61. timer/counter timi ng diagram, with prescaler (f clk_i/o /8) max - 1 clk i/o (clk i/o /1) tcntn tovn clk tn max bottom bottom + 1 max - 1 clk i/o (clk i/o /8) tcntn tovn clk tn max bottom bottom + 1
ata6614q [datasheet] 9240h?auto?10/14 148 figure 5-62 shows the setting of ocf2a in all modes except ctc mode. figure 5-62. timer/counter timing diagram, setting of ocf2a, with prescaler (f clk_i/o /8) figure 5-63 shows the setting of ocf2a and the clearing of tcnt2 in ctc mode. figure 5-63. timer/counter timing diagram, clear timer on compar e match mode, with prescaler (f clk_i/o /8) 5.17.9 asynchronous operation of timer/counter2 when timer/counter2 operates asynchronously, some considerations must be taken. warning: when switching between asynchronous and synch ronous clocking of timer/counter2, the timer registers tcnt2, ocr2x, and tccr2x might be corrupted. a safe procedure for switching clock source is: a. disable the timer/counter2 interrupts by clearing ocie2x and toie2. b. select clock source by setting as2 as appropriate. c. write new values to tcnt2, ocr2x, and tccr2x. d. to switch to asynchronous operation: wait for tcn2xub, o cr2xub, and tcr2xub. e. clear the timer/coun ter2 interrupt flags. f. enable interrupts, if needed. the cpu main clock frequency must be more than four times the oscillator frequency. when writing to one of the registers t cnt2, ocr2x, or tccr2x, t he value is transferred to a temporary register, and latched after two positive edges on tosc1. the user should not write a new value before the contents of the temporary register have been tran sferred to its destination. each of the five mentioned registers have their individual temporary register, which means that e.g. writing to tcnt2 does not disturb an ocr2x write in progress. to detect that a transfer to the destination register has taken pl ace, the asynchronous status register ? assr has been implemented. ocrnx - 1 clk i/o (clk i/o /8) tcntn ocrnx ocfnx clk tn ocrnx ocrnx + 1 ocrnx value ocrnx + 2 top - 1 clk i/o (clk i/o /8) tcntn (ctc) ocrnx ocfnx clk tn top bottom top bottom + 1
149 ata6614q [datasheet] 9240h?auto?10/14 when entering power-save or adc noise reduction mode af ter having written to tcnt2, ocr2x, or tccr2x, the user must wait until the written register has been updated if timer/counter2 is used to wake up the device. otherwise, the mcu will enter sleep mode before the ch anges are effective. this is particul arly important if any of the output compare2 interrupt is used to wake up the device, since the output compare f unction is disabled during writing to ocr2x or tcnt2. if the write cycle is not finished, and the mcu enters sleep mode before the corresponding ocr2xub bit returns to zero, the device will never receive a compare match interrupt, and the mcu will not wake up. if timer/counter2 is used to wake the device up from po wer-save or adc noise reduction mode, precautions must be taken if the user wants to re -enter one of these modes: if re-entering sl eep mode within the tosc 1 cycle, the interrupt will immediately occur and the device wake up again. the result is multiple interrupts and wake-ups within one tosc1 cycle from the first interrupt. if the user is in doubt whether the time before re-entering power-save or adc noise reduction mode is suff icient, the follo wing algorithm can be used to ensure that one tosc1 cycle has elapsed: a. write a value to tccr2x, tcnt2, or ocr2x. b. wait until the correspon ding update busy flag in assr returns to zero. c. enter power-save or adc noise reduction mode. when the asynchronous operation is sele cted, the 32.768khz oscillator for timer/ counter2 is always running, except in power-down and standby modes. after a power-up reset or wake-up from power-down or standby mode, the user should be aware of the fact that this oscillator might take as long as one second to stabilize. the user is advised to wait for at least one second before using timer/counter2 after power-up or wake-up from power-down or standby mode. the contents of all timer/counter2 registers must be considered lost after a wake-up from power-down or standby mode due to unstable clock signal upon start-up, no ma tter whether the oscillator is in use or a clock signal is applied to the tosc1 pin. description of wake up from power-save or adc noise reduction mode when the timer is clocked asynchronously: when the interrupt condition is met, the wake up process is st arted on the following cycle of the timer clock, that is, the timer is always advanced by at least one before the processor can read the counte r value. after wake-up, the mcu is halted for four cycles, it execut es the interrupt routine, and resumes execution from the instruction following sleep. reading of the tcnt2 register shortly after wake-up from power-save may give an incorrect result. since tcnt2 is clocked on the asynchronous tosc clock, reading tcnt 2 must be done through a register synchronized to the internal i/o clock domain. synchronization takes place fo r every rising tosc1 edge. when waking up from power- save mode, and the i/o clock (clk i/o ) again becomes active, tcnt2 will read as the previous value (before entering sleep) until the next rising tosc1 edge. the phase of th e tosc clock after waking up from power-save mode is essentially unpredictable, as it depe nds on the wake-up time. the recommended procedure for reading tcnt2 is thus as follows: a. write any value to either of the registers ocr2x or tccr2x. b. wait for the corresponding update busy flag to be cleared. c. read tcnt2. during asynchronous operation, the synchronization of the interrupt flags for the asynch ronous timer takes 3 processor cycles plus one timer cycle. the timer is therefore advanced by at le ast one before the processor can read the timer value causing the setting of the interrupt flag. the output compare pin is changed on the timer clock and is not synchronized to the processor clock.
ata6614q [datasheet] 9240h?auto?10/14 150 5.17.10 timer/counter prescaler figure 5-64. prescaler for timer/counter2 the clock source for timer/counter2 is named clk t2s . clk t2s is by default conn ected to the main system i/o clock clk i o . by setting the as2 bit in assr, timer/counte r2 is asynchronously clocked from the tosc1 pin. this enables use of timer/counter2 as a real time counter (r tc). when as2 is set, pins tosc1 and tosc2 are disconnected from port c. a crystal can then be connected between the tosc1 and to sc2 pins to serve as an independent clock source for timer/counter2. the pscillator is optim ized for use with a 32.768 khz crystal. for timer/counter2, the possible prescaled selections are: clk t2s /8, clk t2s /32, clk t2s /64, clk t2s /128, clk t2s /256, and clk t2s /1024. additionally, clk t2s as well as 0 (stop) may be selected. setting the psrasy bit in gtccr resets the prescaler. this allows the user to operate with a predictable prescaler. 5.17.11 register description 5.17.11.1 tccr2a ? timer/count er control register a ? bits 7:6 ? com2a1:0: compare match output a mode these bits control the output compare pin (oc2a) behavior. if o ne or both of the com2a1:0 bits are set, the oc2a output overrides the normal port functionality of th e i/o pin it is connected to. however, not e that the data direction register (ddr) bit corresponding to the oc2a pin must be set in order to enable the output driver. when oc2a is connected to the pin, the function of the com2a1:0 bits depends on the wgm22:0 bit setting. table 5-56 shows the com2a1:0 bit functionality when the wgm22:0 bits are set to a normal or ctc mode (non-pwm). timer/counter2 clock source clk t2 clk t2s /8 clk t2s /32 clk t2s /64 clk t2s /128 clk t2s /256 clk t2s /1024 clk i/o tosc1 as2 psrasy clk t2s 10-bit t/c prescaler 0 clear cs20 cs21 cs22 bit 7 6 5 4 3 2 1 0 (0xb0) com2a1 com2a0 com2b1 com2b0 ? ? wgm21 wgm20 tccr2a read/write r/w r/w r/w r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 table 5-56. compare output mode, non-pwm mode com2a1 com2a0 description 0 0 normal port operation, oc0a disconnected. 0 1 toggle oc2a on compare match 1 0 clear oc2a on compare match 1 1 set oc2a on compare match
151 ata6614q [datasheet] 9240h?auto?10/14 table 5-57 shows the com2a1:0 bit functionality when the wgm21:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr2a equals top an d com2a1 is set. in this case, the compare match is ignored, but the set or clear is done at bottom. see section 5.17.7.3 ?fast pwm mode? on page 145 for more details. table 5-58 shows the com2a1:0 bit functionality when the wgm22:0 bits are set to phase correct pwm mode. note: 1. a special case occurs when ocr2a equals top an d com2a1 is set. in this case, the compare match is ignored, but the set or clear is done at top. see section 5.17.7.4 ?phase correc t pwm mode? on page 146 for more details. ? bits 5:4 ? com2b1:0: compare match output b mode these bits control the output compare pin (oc2b) behavior. if o ne or both of the com2b1:0 bits are set, the oc2b output overrides the normal port functionality of th e i/o pin it is connected to. however, not e that the data direction register (ddr) bit corresponding to the oc2b pin must be set in order to enable the output driver. when oc2b is connected to the pin, the function of the com2b1:0 bits depends on the wgm22:0 bit setting. table 5-59 shows the com2b1:0 bit functionality when the wgm22:0 bits are set to a normal or ctc mode (non-pwm). table 5-57. compare output mode, fast pwm mode (1) com2a1 com2a0 description 0 0 normal port operation, oc2a disconnected. 0 1 wgm22 = 0: normal port opera tion, oc0a disconnected. wgm22 = 1: toggle oc2a on compare match. 1 0 clear oc2a on compare match, set oc 2a at bottom, (non-inverting mode). 1 1 set oc2a on compare match, clear oc2a at bottom, (inverting mode). table 5-58. compare output mode, phase correct pwm mode (1) com2a1 com2a0 description 0 0 normal port operation, oc2a disconnected. 0 1 wgm22 = 0: normal port oper ation, oc2a disconnected. wgm22 = 1: toggle oc2a on compare match. 1 0 clear oc2a on compare match when up-counting. set oc2a on compare match when down-counting. 1 1 set oc2a on compare match when up-counting. clear oc2a on compare match when down-counting. table 5-59. compare output mode, non-pwm mode com2b1 com2b0 description 0 0 normal port operation, oc2b disconnected. 0 1 toggle oc2b on compare match 1 0 clear oc2b on compare match 1 1 set oc2b on compare match
ata6614q [datasheet] 9240h?auto?10/14 152 table 5-60 shows the com2b1:0 bit functionality when the wgm22:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr2b equals top an d com2b1 is set. in this case, the compare match is ignored, but the set or clear is done at bottom. see section 5.17.7.4 ?phase correct pwm mode? on page 146 for more details. table 5-61 shows the com2b1:0 bit functionality when the wgm22:0 bits are set to phase correct pwm mode. note: 1. a special case occurs when ocr2b equals top an d com2b1 is set. in this case, the compare match is ignored, but the set or clear is done at top. see section 5.17.7.4 ?phase correc t pwm mode? on page 146 for more details. ? bits 3, 2 ? res: reserved bits these bits are reserved bits in the atmega328p and will always read as zero. ? bits 1:0 ? wgm21:0: waveform generation mode combined with the wgm22 bit found in the t ccr2b register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and w hat type of waveform generation to be used, see table 5-62 on page 152 . modes of operation supported by the time r/counter unit are: normal mode (count er), clear timer on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes (see section 5.17.7 ?modes of operation? on page 143 ). notes: 1. max = 0xff 2. bottom = 0x00 table 5-60. compare output mode, fast pwm mode (1) com2b1 com2b0 description 0 0 normal port operation, oc2b disconnected. 0 1 reserved 1 0 clear oc2b on compare match, set oc 2b at bottom, (non-inverting mode). 1 1 set oc2b on compare match, clear oc2b at bottom, (inverting mode). table 5-61. compare output mode, phase correct pwm mode (1) com2b1 com2b0 description 0 0 normal port operation, oc2b disconnected. 0 1 reserved 1 0 clear oc2b on compare match when up-counting. set oc2b on compare match when down-counting. 1 1 set oc2b on compare match when up-counting. clear oc2b on compare match when down-counting. table 5-62. waveform generation mode bit description mode wgm2 wgm1 wgm0 timer/counter mode of operation top update of ocrx at tov flag set on (1)(2) 0 0 0 0 normal 0xff immediate max 1 0 0 1 pwm, phase correct 0xff top bottom 2 0 1 0 ctc ocra immediate max 3 0 1 1 fast pwm 0xff bottom max 4 1 0 0 reserved ? ? ? 5 1 0 1 pwm, phase correct ocra top bottom 6 1 1 0 reserved ? ? ? 7 1 1 1 fast pwm ocra bottom top
153 ata6614q [datasheet] 9240h?auto?10/14 5.17.11.2 tccr2b ? timer/count er control register b ? bit 7 ? foc2a: force output compare a the foc2a bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr2b is written when operating in pwm mode. when writing a logical one to the foc2a bi t, an immediate compare match is forced on the waveform generation unit. the oc2a output is changed according to its com2a1:0 bits setting. note that the foc2a bit is implemented as a strobe. therefor e it is the value present in the com2a1:0 bits that determ ines the effect of the forced compare. a foc2a strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr2a as top. the foc2a bit is always read as zero. ? bit 6 ? foc2b: force output compare b the foc2b bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr2b is written when operating in pwm mode. when writing a logical one to the foc2b bi t, an immediate compare match is forced on the waveform generation unit. the oc2b output is changed according to its com2b1:0 bits setting. note that the foc2b bit is implemented as a strobe. therefor e it is the value present in the com2b1:0 bits that determ ines the effect of the forced compare. a foc2b strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr2b as top. the foc2b bit is always read as zero. ? bits 5:4 ? res: reserved bits these bits are reserved bits in the atmega328p and will always read as zero. ? bit 3 ? wgm22: waveform generation mode see the description in section 5.17.11.1 ?tccr2a ? timer/counte r control register a? on page 150 . ? bit 2:0 ? cs22:0: clock select the three clock sele ct bits select the clock source to be used by the timer/counter, see table 5-63 on page 153 . if external pin modes are used for the timer/counter0, transit ions on the t0 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. bit 7 6 5 4 3 210 (0xb1) foc2a foc2b ? ? wgm22 cs22 cs21 cs20 tccr2b read/write w w r r r r r/w r/w initial value 0 0 0 0 0 0 0 0 table 5-63. clock select bit description cs22 cs21 cs20 description 0 0 0 no clock source (timer/counter stopped). 0 0 1 clk t2s /(no prescaling) 0 1 0 clk t2s /8 (from prescaler) 0 1 1 clk t2s /32 (from prescaler) 1 0 0 clk t2s /64 (from prescaler) 1 0 1 clk t2s /128 (from prescaler) 1 1 0 clk t 2 s /256 (from prescaler) 1 1 1 clk t 2 s /1024 (from prescaler)
ata6614q [datasheet] 9240h?auto?10/14 154 5.17.11.3 tcnt2 ? timer/counter register the timer/counter register gives direct a ccess, both for read and write operations, to the timer/counter unit 8-bit counter. writing to the tcnt2 register blocks (re moves) the compare match on the followin g timer clock. modifying the counter (tcnt2) while the counter is running, introduces a risk of missing a compare match between tcnt2 and the ocr2x registers. 5.17.11.4 ocr2a ? output compare register a the output compare register a contains an 8-bit value that is continuou sly compared with the counter value (tcnt2). a match can be used to generate an output compare interrup t, or to generate a waveform output on the oc2a pin. 5.17.11.5 ocr2b ? output compare register b the output compare register b contains an 8-bit value that is continuou sly compared with the counter value (tcnt2). a match can be used to generate an output compare interrup t, or to generate a waveform output on the oc2b pin. 5.17.11.6 timsk2 ? timer/counter2 interrupt mask register ? bit 2 ? ocie2b: timer/counter2 outp ut compare match b interrupt enable when the ocie2b bit is written to one and the i-bit in the stat us register is set (one), the timer/counter2 compare match b interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/coun ter2 occurs, i.e., when the ocf2b bit is set in the timer/counter 2 interrupt flag register ? tifr2. ? bit 1 ? ocie2a: timer/counter2 outp ut compare match a interrupt enable when the ocie2a bit is written to one and the i-bit in the stat us register is set (one), the timer/counter2 compare match a interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/coun ter2 occurs, i.e., when the ocf2a bit is set in the timer/counter 2 interrupt flag register ? tifr2. ? bit 0 ? toie2: timer/counter2 overflow interrupt enable when the toie2 bit is written to one and the i-bit in the status register is set (one ), the timer/counter2 overflow interrupt i s enabled. the corresponding interrupt is exec uted if an overflow in timer/counter2 oc curs, i.e., when the tov2 bit is set in the timer/counter2 interrupt flag register ? tifr2. bit 76543210 (0xb2) tcnt2[7:0] tcnt2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 (0xb3) ocr2a[7:0] ocr2a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xb4) ocr2b[7:0] ocr2b read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543 2 1 0 (0x70) ? ? ? ? ? ocie2b ocie2a toie2 timsk2 read/write r r r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0
155 ata6614q [datasheet] 9240h?auto?10/14 5.17.11.7 tifr2 ? timer/counter2 interrupt flag register ? bit 2 ? ocf2b: output compare flag 2 b the ocf2b bit is set (one) when a compare match occurs between the timer/counter2 and the data in ocr2b ? output compare register2. ocf2b is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, ocf2b is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie2b (timer/counter2 compare match interrupt enable), and ocf2b are set (one), the timer/counter2 compare matc h interrupt is executed. ? bit 1 ? ocf2a: output compare flag 2 a the ocf2a bit is set (one) when a compare match occurs between the timer/counter2 and the data in ocr2a ? output compare register2. ocf2a is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, ocf2a is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie2a (timer/counter2 compare match interrupt enable), and ocf2a are set (one), the timer/counter2 compare match interrupt is executed. ? bit 0 ? tov2: timer/counter2 overflow flag the tov2 bit is set (one) when an overflow occurs in time r/counter2. tov2 is cleared by hardware when executing the corresponding interrupt handling vector. alter natively, tov2 is cleared by writing a logic one to the flag. when the sreg i- bit, toie2a (timer/counter2 overflow inte rrupt enable), and tov2 are set (one), the timer/counter2 overflow interrupt is executed. in pwm mode, this bit is set when ti mer/counter2 changes counting direction at 0x00. 5.17.11.8 assr ? asynchronous status register ? bit 7 ? res: reserved bit this bit is reserved and will always read as zero. ? bit 6 ? exclk: enable external clock input when exclk is written to one, and asynchronous clock is selected, the external clock input buffer is enabled and an external clock can be input on timer oscillator 1 (tosc1) pi n instead of a 32khz crystal. writing to exclk should be done before asynchronous operation is selected. note that the crystal oscillator will only run when this bit is zero. ? bit 5 ? as2: asynch ronous timer/counter2 when as2 is written to zero, timer/counte r2 is clocked from the i/o clock, clk i/o . when as2 is written to one, timer/counter2 is clocked from a crystal oscillator connected to the timer oscill ator 1 (tosc1) pin. when the value of as2 is changed, the contents of tcnt2, ocr2a, o cr2b, tccr2a and tccr2b might be corrupted. ? bit 4 ? tcn2ub: timer/counter2 update busy when timer/counter2 operates asynchronously and tcnt2 is written, this bit becomes set. when tcnt2 has been updated from the temporary storage register, this bit is cleared by hardware. a logical zero in this bit indicates that tcnt2 i s ready to be updated with a new value. ? bit 3 ? ocr2aub: output compare register2 update busy when timer/counter2 operates asynchronously and ocr2a is written, this bit becomes set. when ocr2a has been updated from the temporary st orage register, this bit is cleared by hardware. a logical zero in this bi t indicates that ocr2a i s ready to be updated with a new value. bit 76543210 0x17 (0x37) ? ? ? ? ? ocf2b ocf2a tov2 tifr2 read/write r r r r r r/w r/w r/w initial value00000000 bit 7 6 5 4 3 2 1 0 (0xb6) ? exclk as2 tcn2ub ocr2aub ocr2bub tcr2aub tcr2bub assr read/write r r/w r/w r r r r r initial value 0 0 0 0 0 0 0 0
ata6614q [datasheet] 9240h?auto?10/14 156 ? bit 2 ? ocr2bub: output compare register2 update busy when timer/counter2 operates asynchronously and ocr2b is written, this bit becomes set. when ocr2b has been updated from the temporary st orage register, this bit is cleared by hardware. a logical zero in this bi t indicates that ocr2b i s ready to be updated with a new value. ? bit 1 ? tcr2aub: timer/counter control register2 update busy when timer/counter2 operates asynchronously and tccr2a is written, this bit becomes set. when tccr2a has been updated from the temporary st orage register, this bit is cleared by hardware. a logical zero in this bit indicates that tccr2a is ready to be updated with a new value. ? bit 0 ? tcr2bub: timer/counter control register2 update busy when timer/counter2 operates asynchronously and tccr2b is written, this bit becomes set. when tccr2b has been updated from the temporary st orage register, this bit is cleared by hardware. a logical zero in this bit indicates that tccr2b is ready to be updated with a new value. if a write is performed to any of the five timer/counter2 registers while its update busy flag is set, the updated value might get corrupted and cause an unintentional interrupt to occur. the mechanisms for reading tcnt2, o cr2a, ocr2b, tccr2a and tccr2b are different. when reading tcnt2, the actual timer value is read. when read ing ocr2a, ocr2b, tccr2a and tccr2b the value in the temporary storage register is read. 5.17.11.9 gtccr ? general timer/counter control register ? bit 1 ? psrasy: prescaler reset timer/counter2 when this bit is one, the timer/counter2 prescaler will be reset. this bit is normally cleared immediately by hardware. if the bit is written when timer/counter2 is operating in asynchronou s mode, the bit will remain one until the prescaler has been reset. the bit will not be cleared by hardware if th e tsm bit is set. refer to the description of the section ? ?bit 7 ? tsm: timer/counter synchronization mode? on page 138 for a description of the timer/counter synchronization mode. bit 7 6 5 4 3 2 1 0 0x23 (0x43) tsm ? ? ? ? ? psrasy psrsyn c gtccr read/write r/w r r r r r r/w r/w initial value 0 0 0 0 0 0 0 0
157 ata6614q [datasheet] 9240h?auto?10/14 5.18 spi ? serial peripheral interface 5.18.1 features full-duplex, three-wire synchronous data transfer master or slave operation lsb first or msb first data transfer seven programmable bit rates end of transmission interrupt flag write collision flag protection wake-up from idle mode double speed (ck/2) master spi mode 5.18.2 overview the serial peripheral interface (spi) allows high-speed syn chronous data transfer between the atmega328p and peripheral devices or between several avr ? devices. the usart can also be used in master spi mode, see section 5.20 ?usart in spi mode? on page 187 . the prspi bit in section 5.9.10 ?minimizing power consumption? on page 60 must be written to zero to enable spi module. figure 5-65. spi block diagram (1) note: 1. refer to table 5-31 on page 89 for spi pin placement. 8-bit shift register read data buffer spi control register spi status register mstr spi clock (master) spe spi control spi interrupt request select clock logic miso clock 8 88 s m s m m s msb lsb spie spe wcol spif spi2x spi2x spr1 mstr spe dord spr0 dord mstr cpol cpha spr1 spr0 mosi sck ss divider /2/4/8/16/32/64/128 xtal internal data bus pin control logic
ata6614q [datasheet] 9240h?auto?10/14 158 the interconnection between master and slave cpus with spi is shown in figure 5-66 on page 158 . the system consists of two shift regist ers, and a master clock generator. the spi master initiates the communication cycle when pulling low the slave select ss pin of the desired slave. ma ster and slave prepare the data to be sent in their respective shift registers, and the master generates the required clock pulses on the sck line to interchange data. data is always shifted from master to slave on the master out ? slave in, mosi, li ne, and from slave to master on the master in ? slave out, miso, line. after each data packet, the master will synchronize the slave by pulling high the slave select, ss , line. when configured as a master, the spi in terface has no automatic control of the ss line. this must be handled by user software before communication can start. when this is done, writing a byte to the spi data register starts the spi clock generator, and the hardware shifts the eight bits into the slave. after shif ting one byte, the spi clock generator stops, setti ng the end of transmission flag (spif). if the spi interrupt enable bit (spie) in the spcr register is set, an interrupt is requested. the master may continue to shift t he next byte by writing it into spdr, or signal the end of packet by pulling high the slave select, ss line. the last incoming byte will be ke pt in the buffer register for later use. when configured as a slave, the spi interface will rema in sleeping with miso tri- stated as long as the ss pin is driven high. in this state, software may update the contents of the spi data register, spdr, but the data will not be shifted out by incoming clock pulses on the sck pin until the ss pin is driven low. as one byte has been completely shifted, the end of transmission flag, spif is set. if the spi interrupt enable bit, spie, in the spcr r egister is set, an interrupt is requested. the slave may continue to place new data to be sent into spdr befor e reading the incoming data. the last incoming byte will be kept in the buffer register for later use. figure 5-66. spi master-slave interconnection the system is single buffered in the transmi t direction and double buffered in the receive directio n. this means that bytes to be transmitted cannot be written to the spi data register before the entire shift cycle is co mpleted. when receiving data, however, a received character must be read from the spi dat a register before the next character has been completely shifted in. otherwise, the first byte is lost. in spi slave mode, the control logic will sample the incoming si gnal of the sck pin. to ensure correct sampling of the clock signal, the minimum low and high periods should be: low periods: longer than 2 cpu clock cycles. high periods: longer than 2 cpu clock cycles. when the spi is enabled, the data dire ction of the mosi, miso, sck, and ss pins is overridden according to table 5-64 on page 158 . for more details on automatic port overrides, refer to section 5.13.3 ?alternate port functions? on page 87 . note: 1. see section 5.13.3.1 ?alternate functions of port b? on page 89 for a detailed description of how to define the direction of the user defined spi pins. table 5-64. spi pin overrides (1) pin direction, master spi direction, slave spi mosi user defined input miso input user defined sck user defined input ss user defined input lsb slave msb 8 bit shift register lsb shift enable master msb ss sck ss sck mosi mosi miso miso 8 bit shift register spi clock generator
159 ata6614q [datasheet] 9240h?auto?10/14 the following code examples show how to initialize the spi as a master and how to perform a simple transmission. ddr_spi in the examples must be replaced by the actual dat a direction register contro lling the spi pins. dd_mosi, dd_miso and dd_sck must be replaced by t he actual data direction bits for these pi ns. e.g. if mosi is placed on pin pb5, replace dd_mosi with ddb5 and ddr_spi with ddrb. note: 1. see section 5.5 ?about code examples? on page 32 . assembly code example (1) spi_masterinit: ; set mosi and sck output, all others input ldi r17,(1< ata6614q [datasheet] 9240h?auto?10/14 160 the following code examples show how to initialize the spi as a slave and how to perform a simple reception. note: 1. see section 5.5 ?about code examples? on page 32 . assembly code example (1) spi_slaveinit: ; set miso output, all others input ldi r17,(1< 161 ata6614q [datasheet] 9240h?auto?10/14 5.18.3 ss pin functionality 5.18.3.1 slave mode when the spi is configured as a slave, the slave select (ss) pin is always input. when ss is held low, the spi is activated, and miso becomes an output if configured so by the user. all other pins are inputs. when ss is driven high, all pins are inputs, and the spi is passive, which means that it will not re ceive incoming data. note that the spi logic will be reset once the ss pin is driven high. the ss pin is useful for packet/byte synchronization to keep the slave bit counter synchronous with the master clock generator. when the ss pin is driven high, the spi slave will immediat ely reset the send and receive logic, and drop any partially received data in the shift register. 5.18.3.2master mode when the spi is configured as a master (mstr in spcr is set), the user can determine the direction of the ss pin. if ss is configured as an output, the pin is a general output pin which does not affect the spi system. typically, the pin will be driving the ss pin of the spi slave. if ss is configured as an input, it must be hel d high to ensure master spi operation. if the ss pin is driven low by peripheral circuitry when the spi is conf igured as a master with the ss pin defined as an input, the spi system interprets this as another master select ing the spi as a slave and starting to send data to it. to avoid bu s contention, the spi system takes the following actions: 1. the mstr bit in spcr is cleared and the spi system becomes a slave. as a result of the spi becoming a slave, the mosi and sck pins become inputs. 2. the spif flag in spsr is set, and if t he spi interrupt is enabled, and the i-bit in sreg is set, the interrupt routine will be executed. thus, when interrupt-driven spi transmission is used in master mode, and there exis ts a possibility that ss is driven low, the interrupt should always check that the mstr bit is still set. if the mstr bit has been cleared by a slave select, it must be se t by the user to re-enable spi master mode. 5.18.4 data modes there are four combinations of sck phase and polarity with respect to serial data, which are determined by control bits cpha and cpol. the spi data transfer formats are shown in figure 5-67 and figure 5-68 on page 162 . data bits are shifted out and latched in on opposite edges of the sck signal, ensuring sufficient time for data signals to stabilize. this is clearly seen by summarizing table 5-66 on page 163 and table 5-67 on page 163 , as done in table 5-65 . table 5-65. spi modes spi mode conditions leading edge trailing edge 0 cpol=0, cpha=0 sample (rising) setup (falling) 1 cpol=0, cpha=1 setup (rising) sample (falling) 2 cpol=1, cpha=0 sample (falling) setup (rising) 3 cpol=1, cpha=1 setup (falling) sample (rising)
ata6614q [datasheet] 9240h?auto?10/14 162 figure 5-67. spi transfer format with cpha = 0 figure 5-68. spi transfer format with cpha = 1 lsb msb bit 1 bit 6 bit 2 bit 5 bit 3 bit 4 bit 4 bit 3 bit 5 bit 2 bit 6 bit 1 msb lsb msb first (dord = 0) lsb first (dord =1) sck (cpol = 0) mode 0 sck (cpol = 1) mode 2 ss sample i mosi/miso change 0 mosi pin change 0 miso pin lsb msb bit 1 bit 6 bit 2 bit 5 bit 3 bit 4 bit 4 bit 3 bit 5 bit 2 bit 6 bit 1 msb lsb msb first (dord = 0) lsb first (dord =1) sck (cpol = 0) mode 1 sck (cpol = 1) mode 3 ss sample i mosi/miso change 0 mosi pin change 0 miso pin
163 ata6614q [datasheet] 9240h?auto?10/14 5.18.5 register description 5.18.5.1 spcr ? spi control register ? bit 7 ? spie: spi interrupt enable this bit causes the spi interrupt to be executed if spif bit in the spsr register is set and the if the global interrupt enable bit in sreg is set. ? bit 6 ? spe: spi enable when the spe bit is written to one, the spi is enabled . this bit must be set to enable any spi operations. ? bit 5 ? dord: data order when the dord bit is written to one, the l sb of the data word is transmitted first. when the dord bit is written to zero, the msb of the data word is transmitted first. ? bit 4 ? mstr: master/slave select this bit selects master spi mode when written to one, and slave spi mode when written logic zero. if ss is configured as an input and is driven low while mstr is set, mstr will be clea red, and spif in spsr will become set. the user will then have to set mstr to re-enab le spi master mode. ? bit 3 ? cpol: clock polarity when this bit is written to one, sck is high when idle. wh en cpol is written to zero, sck is low when idle. refer to figure 5-67 and figure 5-68 for an example. the cpol functionality is summarized below: ? bit 2 ? cpha: clock phase the settings of the clock phase bit (cpha) determine if data is sampled on the leading (first) or trailing (last) edge of sck. refer to figure 5-67 and figure 5-68 for an example. the cpol functionality is summarized below: ? bits 1, 0 ? spr1, spr0: spi clock rate select 1 and 0 these two bits control the sck rate of the device configur ed as a master. spr1 and spr0 have no effect on the slave. bit 76543210 0x2c (0x4c) spie spe dord mstr cpol cpha spr1 spr0 spcr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 5-66. cpol functionality cpol leading edge trailing edge 0 rising falling 1 falling rising table 5-67. cpha functionality cpha leading edge trailing edge 0 sample setup 1 setup sample
ata6614q [datasheet] 9240h?auto?10/14 164 the relationship between sck and the oscillator clock frequency f osc is shown in the following table: 5.18.5.2 spsr ? spi status register ? bit 7 ? spif: spi interrupt flag when a serial transfer is complete, the spif flag is set. an in terrupt is generated if spie in spcr is set and global interrupt s are enabled. if ss is an input and is driven low when the spi is in ma ster mode, this will also set the spif flag. spif is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, the spif bit is cleared by first reading the spi status register with spif se t, then accessing the spi data register (spdr). ? bit 6 ? wcol: write collision flag the wcol bit is set if the spi data register (spdr) is writte n during a data transfer. the wcol bit (and the spif bit) are cleared by first reading the spi stat us register with wcol set, and then accessing the spi data register. ? bit 5..1 ? res: reserved bits these bits are reserved bits in the atmega328p and will always read as zero. ? bit 0 ? spi2x: double spi speed bit when this bit is written logic one the spi speed (sck fr equency) will be doubled when the spi is in master mode (see table 5-68 ). this means that the minimum sck period will be two cpu clock periods. when the spi is configured as slave, the spi is only guaranteed to work at f osc /4 or lower. the spi interface on the atmega328p is also used for pr ogram memory and eeprom downloading or uploading. see section 5.27.8 ?serial downloading? on page 274 for serial programming and verification. 5.18.5.3 spdr ? spi data register the spi data register is a read/ write register used for data transfer between th e register file and the spi shift register. wri ting to the register initiates data transmission. reading the regi ster causes the shift register receive buffer to be read. table 5-68. relationship between sck and the oscillator frequency spi2x spr1 spr0 sck frequency 0 0 0 f osc / 4 0 0 1 f osc / 16 0 1 0 f osc / 64 0 1 1 f osc / 128 1 0 0 f osc / 2 1 0 1 f osc / 8 1 1 0 f osc / 32 1 1 1 f osc / 64 bit 76543210 0x2d (0x4d) spif wcol ? ? ? ? ? spi2x spsr read/write r r r r r r r r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x2e (0x4e) msb lsb spdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial valuexxxxxxxxu ndefined
165 ata6614q [datasheet] 9240h?auto?10/14 5.19 usart0 5.19.1 features full duplex operation (independent serial receive and transmit registers) asynchronous or synchronous operation master or slave clocked synchronous operation high resolution baud rate generator supports serial frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits odd or even parity generation and parity check supported by hardware data overrun detection framing error detection noise filtering includes false start bit detection and digital low pass filter three separate interrupts on tx complete, tx data register empty and rx complete multi-processor communication mode double speed asynchronous communication mode 5.19.2 overview the universal synchronous and asynchronous serial receiver and transmitter (usart) is a highly flexible serial communication device. the usart0 can also be used in master spi mode, see section 5.20 ?usart in spi mode? on page 187 . the power reduction usart bit, prusart0, in section 5.9.10 ?minimizing power consumption? on page 60 must be disabled by writing a logical zero to it. a simplified block diagram of the usart transmitter is shown in figure 5-69 on page 166 . cpu accessible i/o registers and i/o pins are shown in bold. the dashed boxes in the block diagram separate the three main parts of the usart (listed fr om the top): clock generator, transmitter and receiver. control register s are shared by all units. the clock gener ation logic consists of synchronization logic for external clock input used by synchronous slave opera tion, and the baud rate generator. the xckn (transfer clock) pin is only used by synchronous transfer m ode. the transmitter consists of a single write buffer, a serial shift register, pari ty generator and control logic for handling diff erent serial frame formats. the write buffer allows a continuous transfer of data without any delay between frames. the receiv er is the most complex part of the usart module due to its clock and data recovery units. the recovery units are used for asynchronous data reception. in addition to the recovery units, the receiver includes a parity checker, control logic, a shift register and a two level receive buffer (udrn). the receiver supports the same frame formats as the transmitter, and can de tect frame error, data overrun and parity errors.
ata6614q [datasheet] 9240h?auto?10/14 166 figure 5-69. usart block diagram (1) note: 1. refer to table 5-37 on page 94 for usart0 pin placement. transmit shift register receive shift register data recovery clock recovery parity checker parity generator pin control tx control pin control pin control rx control udrn (transmit) transmitter clock generator receiver ucsrna ucsrnc ucsrnb sync logic osc udrn (receive) data bus baud rate generator ubrrn[h:l] xckn rxdn txdn
167 ata6614q [datasheet] 9240h?auto?10/14 5.19.3 clock generation the clock generation logic generates the base clock for the transmitter and receiver. the usart supports four modes of clock operation: normal asynchronous, double speed asynchro nous, master synchronous and slave synchronous mode. the umseln bit in usart control and st atus register c (ucsrnc) selects between asynchronous and synchronous operation. double speed (asynchronous mo de only) is controlled by the u2xn fo und in the ucsrna register. when using synchronous mode (umseln = 1), the data direction register for the xckn pin (ddr_xckn) controls whether the clock source is internal (master mode) or external (slave mode) . the xckn pin is only active when using synchronous mode. figure 5-70 shows a block diagram of the clock generation logic. figure 5-70. clock generati on logic, block diagram signal description: txclk transmitter clock (internal signal). rxclk receiver base clock (internal signal). xcki input from xck pin (internal signal). used for synchronous slave operation. xcko clock output to xck pin (internal signal ). used for synchronous master operation. fosc xtal pin frequency (system clock). 5.19.3.1 internal clock generation ? the baud rate generator internal clock generation is used for the asynchronous and the synchronous master modes of operation. the description in this section refers to figure 5-70 . the usart baud rate register (ubrrn) a nd the down-counter connect ed to it function as a programmable prescaler or baud rate generator. the down-counter, running at system clock (f osc ), is loaded with the ubrrn value each time the counter has counted down to zero or when the ubrrnl register is written. a clock is generated each time the counter reaches zero. this clock is the baud rate generator clock output (= f osc /(ubrrn+1)). the transmitter divides the baud rate generator clock output by 2, 8 or 16 depending on mode. the baud rate generator output is used directly by the receiver?s clock and data recovery units. however, the recovery units us e a state machine that uses 2, 8 or 16 states depending on mode set by the state of the um seln, u2xn and ddr_xckn bits. sync register edge detector prescaling down-counter /2 xckn pin /4 0 0 1 1 0 1 1 0 /2 ubrrn ddr_xckn ucpoln u2xn ddr_xckn ubrrn+1 txclk rxclk umseln foscn osc xcki xcko
ata6614q [datasheet] 9240h?auto?10/14 168 table 5-69 contains equations for calculating the baud rate (in bits per second) and for calculating the ubrrn value for each mode of operation using an internally generated clock source. baud baud rate (in bits per second, bps) f osc system oscillator clock frequency ubrrn contents of the ubrrnh and ubrrnl registers, (0-4095) some examples of ubrrn values for some system clock frequencies are found in table 5-77 (see 185 ). 5.19.3.2 double speed operation (u2xn) the transfer rate can be doubled by setting the u2xn bit in ucsrna. setting this bit only has effect for the asynchronous operation. set this bit to zero when using synchronous operation. setting this bit will reduce the divisor of the baud rate divi der from 16 to 8, effectively doubling the transfer rate for asynchronous communication. note however that the receiver will in this case only use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery, and ther efore a more accurate baud rate setting and system clock are required when this mode is used. for the transmitter, there are no downsides. 5.19.3.3 external clock external clocking is used by the synchronous slave modes of operation. the description in this section refers to figure 5-70 for details. external clock input from the xckn pin is sampled by a synchro nization register to minimize the chance of meta-stability. the output from the synchronization regi ster must then pass through an edge de tector before it can be used by the transmitter and receiver. this process introduces a two cpu clock period delay and therefore the maximum external xckn clock frequency is limited by the following equation: note that f osc depends on the stability of the system clock source. it is therefore recommended to add some margin to avoid possible loss of data due to frequency variations. table 5-69. equations for calculat ing baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrrn value asynchronous normal mode (u2xn = 0) asynchronous double speed mode (u2xn = 1) synchronous master mode note: 1. the baud rate is defined to be the transfer rate in bit per second (bps) baud f osc 16 ubrr n 1 + () ---------------------------------------- - = ubrr n f osc 16 baud ---------------------- - 1 ? = baud f osc 8 ubrr n 1 + () ------------------------------------- - = ubrr n f osc 8 baud ------------------- - 1 ? = baud f osc 2 ubrr n 1 + () ------------------------------------- - = ubrr n f osc 2 baud ------------------- - 1 ? = f xck f osc 4 ----------- <
169 ata6614q [datasheet] 9240h?auto?10/14 5.19.3.4 synchronous clock operation when synchronous mode is used (umseln = 1), the xckn pin will be used as either clock input (slave) or clock output (master). the dependency between the clock edges and data sa mpling or data change is the same. the basic principle is that data input (on rxdn) is sampled at the opposite xckn clock edge of the edge the data output (txdn) is changed. figure 5-71. synchronous mode xckn timing the ucpoln bit ucrsc selects which xckn clock edge is used for data sampling and which is used for data change. as figure 5-71 shows, when ucpoln is zero the data will be changed at rising xckn edge and sampled at falling xckn edge. if ucpoln is set, the data will be changed at falling xckn edge and sampled at rising xckn edge. 5.19.4 frame formats a serial frame is defined to be one character of data bits with synchronization bits (start and stop bits), and optionally a pa rity bit for error checking. the usart accepts all 30 comb inations of the following as valid frame formats: 1 start bit 5, 6, 7, 8, or 9 data bits no, even or odd parity bit 1 or 2 stop bits a frame starts with the start bit followed by the least signific ant data bit. then the next data bits, up to a total of nine, a re succeeding, ending with the most significant bit. if enabled, the parity bit is insert ed after the data bits, before the stop b its. when a complete frame is transmitted, it can be directly follow ed by a new frame, or the communication line can be set to an idle (high) state. figure 5-72 illustrates the possible combinations of the fr ame formats. bits inside brackets are optional. figure 5-72. frame formats st start bit, always low. (n) data bits (0 to 8). p parity bit. can be odd or even. sp stop bit, always high. idle no transfers on the communication line (rxdn or txdn). an idle line must be high. xck rxd/txd xck ucpol = 1 ucpol = 0 rxd/txd sample sample st 0 1 2 3 4 [5] [6] [7] [8] (st/idle) (idle) frame [p] sp1 [sp2]
ata6614q [datasheet] 9240h?auto?10/14 170 the frame format used by the usart is set by the ucszn 2:0, upmn1:0 and usbsn bits in ucsrnb and ucsrnc. the receiver and transmitter use the same setting. note that c hanging the setting of any of thes e bits will corrupt all ongoing communication for both the receiver and transmitter. the usart character size (ucszn2:0) bits select the number of data bits in the frame. the usart parity mode (upmn1:0) bits enable and set the type of parity bit. the selection between one or two stop bits is done by the usart stop bit select (usbsn) bit. the receiver ignores the second stop bit. an fe (f rame error) will therefore only be detected in the cases where the first stop bit is zero. 5.19.4.1 parity bit calculation the parity bit is calculated by doing an exclusive-or of all the data bits. if odd parity is used, the result of the exclusive or is inverted. the relation between the parity bit and data bits is as follows: p even parity bit using even parity p odd parity bit using odd parity d n data bit n of the character if used, the parity bit is located between the last data bit and first stop bit of a serial frame. p even d n 1 ? d 3 d 2 d 1 d 0 0 p odd d n 1 ? d 3 d 2 d 1 d 0 1 = =
171 ata6614q [datasheet] 9240h?auto?10/14 5.19.5 usart in itialization the usart has to be initialized before any communication can take place. the initialization process normally consists of setting the baud rate, setting frame format and enabling the tran smitter or the receiver depending on the usage. for interrupt driven usart operation, the global interrupt flag should be cl eared (and interrupts globally disabled) when doing the initialization. before doing a re-initialization with changed baud rate or fr ame format, be sure that there are no ongoing transmissions during the period the registers are changed. the txcn flag c an be used to check that the transmitter has completed all transfers, and the rxc flag can be used to check that there are no unread data in the receive buffer. note that the txcn flag must be cleared before each transmission (before ud rn is written) if it is used for this purpose. the following simple usart initialization code examples sh ow one assembly and one c function that are equal in functionality. the examples assume asyn chronous operation using polling (no interr upts enabled) and a fixed frame format. the baud rate is given as a function parameter. for the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. note: 1. see section 5.5 ?about code examples? on page 32 . more advanced initialization routines can be made that include frame format as parameters, disable interrupts and so on. however, many applications use a fixed setting of the baud and control registers, and for these types of applications the initialization code can be placed directly in the main routi ne, or be combined with initialization code for other i/o modules. assembly code example (1) usart_init: ; set baud rate out ubrrnh, r17 out ubrrnl, r16 ; enable receiver and transmitter ldi r16, (1<>8); ubrr0l = ( unsigned char )ubrr; enable receiver and transmitter */ ucsr0b = (1< ata6614q [datasheet] 9240h?auto?10/14 172 5.19.6 data transmission ? the usart transmitter the usart transmitter is enabled by setting the transmit enable (txen) bit in the ucsrnb register. when the transmitter is enabled, the normal port operation of th e txdn pin is overridden by the usart a nd given the function as the transmitter?s serial output. the baud rate, mode of operation and frame form at must be set up once before doing any transmissions. if synchronous operation is used, the clock on the xckn pin will be overridden and used as transmission clock. 5.19.6.1 sending frames with 5 to 8 data bit a data transmission is initiated by loading the transmit buffer with the data to be transmitted. the cpu can load the transmit buffer by writing to the udrn i/o location. the buffered data in t he transmit buffer will be moved to the shift register when t he shift register is ready to send a new fram e. the shift register is lo aded with new data if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previous fr ame is transmitted. when the shift register is loaded wi th new data, it will transfer one complete frame at the rate give n by the baud register, u2xn bit or by xckn depending on mode of operation. the following code examples show a simple u sart transmit function based on polling of the data register empty (udren) flag. when using frames with less than eight bits, the most si gnificant bits written to the udrn are ignored. the usart has to be initialized before the function can be used. for the asse mbly code, the data to be sent is assumed to be stored in register r16. note: 1. see section 5.5 ?about code examples? on page 32 . the function simply waits for the transmit buffer to be empty by checking the udre n flag, before loading it with new data to be transmitted. if the data register empt y interrupt is utilized, the interrupt r outine writes the data into the buffer. assembly code example (1) usart_transmit: ; wait for empty transmit buffer sbis ucsrna,udren rjmp usart_transmit ; put data (r16) into buffer, sends the data out udrn,r16 ret c code example (1) void usart_transmit( unsigned char data ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< 173 ata6614q [datasheet] 9240h?auto?10/14 5.19.6.2 sending frames with 9 data bit if 9-bit characters are used (ucszn = 7), the ninth bit must be written to the txb8 bit in ucsrnb before the low byte of the character is written to udrn. the following code examples show a transmit function that handles 9-bit characters. for the assembly code, the data to be sent is assu med to be stored in registers r17:r16. notes: 1. these transmit functions are written to be general func tions. they can be optimized if the contents of the ucs- rnb is static. for example, only the txb8 bit of the ucsrnb register is used after initialization. 2. see section 5.5 ?about code examples? on page 32 . the ninth bit can be used for indicating an address fram e when using multi processor communication mode or for other protocol handling as for example synchronization. 5.19.6.3 transmitter flags and interrupts the usart transmitter has two flags that indicate its state: usart data regist er empty (udren) and transmit complete (txcn). both flags can be used for generating interrupts. the data register empty (udren) flag indica tes whether the transmit buffer is ready to receive new data. this bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not yet been moved into the shift register. for compat ibility with future devices, always write th is bit to zero when writing the ucsrna register. when the data register empty interrupt enable (udrien) bit in ucsrnb is written to one, the usart data register empty interrupt will be executed as long as udren is set (provided that global interrupts are enabled). udren is cleared by writing udrn. when interrupt-driven data transmission is used, the data register empty interrupt routin e must either write new data to udrn in order to clear udren or disable the data register empty interrupt, otherwise a new interrupt will occur once the interrupt rout ine terminates. the transmit complete (txcn) flag bit is set one when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer. the txcn flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txcn flag is useful in half-dupl ex communication interfaces (like the rs-485 standard), where a transmitting application must enter receive mode and free the communication bus immediately after completing the transmission. assembly code example (1)(2) usart_transmit: ; wait for empty transmit buffer sbis ucsrna,udren rjmp usart_transmit ; copy 9th bit from r17 to txb8 cbi ucsrnb,txb8 sbrc r17,0 sbi ucsrnb,txb8 ; put lsb data (r16) into buffer, sends the data out udrn,r16 ret c code example (1)(2) void usart_transmit( unsigned int data ) { /* wait for empty transmit buffer */ while ( !( ucsrna & (1< ata6614q [datasheet] 9240h?auto?10/14 174 when the transmit compete interrupt enable (txcien) bit in ucsrnb is set, the usart transmit complete interrupt will be executed when the txcn flag becomes se t (provided that global interrupts ar e enabled). when the transmit complete interrupt is used, the interrupt handling routine does not have to clear the txcn flag, this is done automatically when the interrupt is executed. 5.19.6.4 parity generator the parity generator calculates the parity bit for the serial frame data. when parity bit is enabled (upmn1 = 1), the transmitter control logic inserts the parity bit between the last data bit and the first stop bit of the frame that is sent. 5.19.6.5 disabling the transmitter the disabling of the transmitter (setti ng the txen to zero) will not become effe ctive until ongoing and pending transmissions are completed, i.e., when the transmit shift register and transmit buffer register do not contain data to be transmitted. when disabled, the transmitter will no longer override the txdn pin. 5.19.7 data reception ? the usart receiver the usart receiver is enabled by writing the receive enable (r xenn) bit in the ucsrnb regist er to one. when the receiver is enabled, the normal pin operation of the rxdn pin is overridden by the usart and given the function as the receiver?s serial input. the baud rate, mode of operation and frame format must be set up once before any serial reception can be done. if synchronous operation is used, the clo ck on the xckn pin will be used as transfer clock. 5.19.7.1 receiving frames with 5 to 8 data bits the receiver starts data reception when it detects a valid start bit. each bit that follows the start bit will be sampled at th e baud rate or xckn clock, and shifted into the receive shift r egister until the first stop bit of a frame is received. a second stop bit will be ignored by the receiver. when the first stop bit is re ceived, i.e., a complete serial frame is present in the recei ve shift register, the contents of the shift re gister will be moved into the receive buffe r. the receive buffer can then be read b y reading the udrn i/o location. the following code example shows a simple usart receive f unction based on polling of the receive complete (rxcn) flag. when using frames with less than eight bits the most significant bits of the da ta read from the udrn will be masked to zero. the usart has to be initialized before the function can be used. note: 1. see section 5.5 ?about code examples? on page 32 . for i/o registers located in extended i/o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. the function simply waits for data to be present in the rece ive buffer by checking the rxcn flag, before read ing the buffer and returning the value. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsrna, rxcn rjmp usart_receive ; get and return received data from buffer in r16, udrn ret c code example (1) unsigned char usart_receive( void ) { /* wait for data to be received */ while ( !(ucsrna & (1< 175 ata6614q [datasheet] 9240h?auto?10/14 5.19.7.2 receiving fram es with 9 data bits if 9-bit characters are used (ucszn=7) th e ninth bit must be read from the rxb8n bit in ucsrnb before reading the low bits from the udrn. this rule applies to the fen, dorn and upen st atus flags as well. read stat us from ucsrna, then data from udrn. reading the udrn i/o location will change the stat e of the receive buffer fifo and consequently the txb8n, fen, dorn and upen bits, which all are stored in the fifo, will change. the following code example shows a simple usart receive func tion that handles both nine bit characters and the status bits. note: 1. see section 5.5 ?about code examples? on page 32 . for i/o registers located in extended i/ o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. the receive function example reads all the i/o registers into the register file before any comput ation is done. this gives an optimal receive buffer utilization since the buffer location read will be free to accept ne w data as early as possible. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsrna, rxcn rjmp usart_receive ; get status and 9th bit, then data from buffer in r18, ucsrna in r17, ucsrnb in r16, udrn ; if error, return -1 andi r18,(1<> 1) & 0x01; return ((resh << 8) | resl); }
ata6614q [datasheet] 9240h?auto?10/14 176 5.19.7.3 receive compete flag and interrupt the usart receiver has one flag th at indicates the receiver state. the receive complete (rxcn) flag indicates if there are unrea d data present in the receive buf fer. this flag is one when unread data exist in the receive buffer, and zero when the receiv e buffer is empty (i.e., does no t contain any unread data). if the receiver is disabled (rxenn = 0), the receive buffer will be flushed and consequently the rxcn bit will become zero. when the receive complete interrupt enable (rxcien) in uc srnb is set, the usart receive complete interrupt will be executed as long as the rxcn flag is set (provided that global interrupts are en abled). when interrupt-driven data reception is used, the receive complete routine must read the received da ta from udrn in order to cl ear the rxcn flag, otherwise a new interrupt will occur once the interrupt routine terminates. 5.19.7.4 receiver error flags the usart receiver has three error flags: frame error (fen ), data overrun (dorn) and parity error (upen). all can be accessed by reading ucsrna. common for the error flags is that they are located in the receive buffer together with the frame for which they indicate the error status. due to the buff ering of the error flags, the ucsrna must be read before the receive buffer (udrn), since reading the udrn i/o location changes the buffer read location. another equality for the error flags is that they can not be altered by so ftware doing a write to the flag location. ho wever, all flags must be set to zero wh en the ucsrna is written for upward compatibility of future u sart implementations. none of the error flags can generate interrupts. the frame error (fen) flag indicates the state of the first stop bit of the next readable frame st ored in the receive buffer. t he fen flag is zero when the stop bit was correctly read (as one), and the fen flag will be one when the stop bit was incorrect (zero). this flag can be used for detectin g out-of-sync conditions, detecting break conditions and protocol handling. the fen flag is not affected by the setting of the usbsn bit in ucsrnc si nce the receiver ignores all, e xcept for the first, stop bits. for compatibility with future de vices, always set this bit to zero when writing to ucsrna. the data overrun (dorn) flag indicates data loss due to a re ceiver buffer full condition. a data overrun occurs when the receive buffer is full (two characters), it is a new character waiting in the receiv e shift register, and a new start bit is de tected. if the dorn flag is set there was one or more serial frame lost between the frame last r ead from udrn, and the next frame read from udrn. for compatibility with future devices, always writ e this bit to zero when writing to ucsrna. the dorn flag is cleared when the frame received was successfully mo ved from the shift register to the receive buffer. the parity error (upen) flag indicates that the next frame in the receive buffer had a parity error when received. if parity check is not enabled the upen bit will always be read zero. for compatibility with future devices, always set this bit to zero when writing to ucsrna. for more details see section 5.19.4.1 ?parity bit calculation? on page 170 and section 5.19.7.5 ?parity checker? on page 176 . 5.19.7.5 parity checker the parity checker is active when the high usart parity mode (u pmn1) bit is set. type of parit y check to be performed (odd or even) is selected by the upmn0 bit. when enabled, the parity checker calculates the parity of the data bits in incoming frames and compares the result with the pari ty bit from the serial frame. the result of the check is stored in the receive buff er together with the received data and stop bits . the parity error (upen) flag can then be read by software to check if the frame had a parity error. the upen bit is set if the next character that can be read from the receive buffer had a parity error when received and the parity checking was enabled at that point (upmn1 = 1). this bit is valid until the receive buffer (udrn) is read. 5.19.7.6 disabling the receiver in contrast to the transmitter, disabling of the receiver will be immediate. data from ongoing receptions will therefore be los t. when disabled (i.e., the rxenn is set to ze ro) the receiver will no longer override th e normal function of the rxdn port pin. the receiver buffer fifo will be flushed when the receiver is disabled. remaining data in the buffer will be lost.
177 ata6614q [datasheet] 9240h?auto?10/14 5.19.7.7 flushing the receive buffer the receiver buffer fifo will be flushed wh en the receiver is disabled , i.e., the buffer will be empt ied of its contents. unrea d data will be lost. if the buffer has to be flushed during normal operation, due to for instance an error condition, read the ud rn i/o location until the rxcn flag is cleared. the follow ing code example shows how to flush the receive buffer. note: 1. see section 5.5 ?about code examples? on page 32 . for i/o registers located in extended i/o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. 5.19.8 asynchronous data reception the usart includes a clock recovery and a data recovery unit for handling asynchronous data reception. the clock recovery logic is used for synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames at the rxdn pin. the data recovery logic samples and low pass filters each incoming bit, thereby improving the noise immunity of the receiver. the asynchronous reception operati onal range depends on the accuracy of the internal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. 5.19.8.1 asynchronous clock recovery the clock recovery logic synch ronizes internal cl ock to the incoming serial frames. figure 5-73 illustrates the sampling process of the start bit of an incoming frame. the sample rate is 16 times the baud rate for normal mode, and eight times the baud rate for double speed mode. the horizontal arrows illustra te the synchronization variation due to the sampling process. note the larger time variation when using the double spee d mode (u2xn = 1) of operation. samples denoted zero are samples done when the rxdn line is idle (i.e., no communication activity). figure 5-73. start bit sampling when the clock recovery logic detects a high (idle) to low (sta rt) transition on the rxdn line, the start bit detection sequenc e is initiated. let sample 1 denote the first zero-sample as shown in the figure. the clock recovery logic then uses samples 8, 9, and 10 for normal mode, and samples 4, 5, and 6 for double speed mode (indicated with sample numbers inside boxes on the figure), to decide if a valid start bi t is received. if two or more of these th ree samples have logical high levels (the ma jority wins), the start bit is rejected as a noise spike and the receiver starts looking for the next high to low-transition. if howev er, a valid start bit is detected, t he clock recovery logic is synchronized and the data recovery can begin. the synchronization process is repeated for each start bit. assembly code example (1) usart_flush: sbis ucsrna, rxcn ret in r16, udrn rjmp usart_flush c code example (1) void usart_flush( void ) { unsigned char dummy; while ( ucsrna & (1< ata6614q [datasheet] 9240h?auto?10/14 178 5.19.8.2 asynchronous data recovery when the receiver clock is synchronized to the start bit, the data recovery can begi n. the data recovery unit uses a state machine that has 16 states for each bit in normal m ode and eight states for each bit in double speed mode. figure 5-74 shows the sampling of the data bits and the par ity bit. each of the samples is given a number that is equal to the state of the recovery unit. figure 5-74. sampling of data and parity bit the decision of the logic level of the received bit is taken by doing a majority voting of the logic value to the three samples in the center of the received bit. the center samples are emphas ized on the figure by having the sample number inside boxes. the majority voting process is done as follows: if two or all th ree samples have high levels, the received bit is registered to be a logic 1. if two or all three samples have low levels, the received bit is registered to be a logic 0. this majority voting process acts as a low pass filter for the incoming signal on the rxdn pin. the recovery process is then repeated until a complete frame is received. including the first stop bit. note that the receiver only uses the first stop bit of a frame. figure 5-75 shows the sampling of the stop bit and the earliest po ssible beginning of the start bit of the next frame. figure 5-75. stop bit sampling and next start bit sampling the same majority voting is done to the stop bit as done for t he other bits in the frame. if the stop bit is registered to have a logic 0 value, the frame error (fen) flag will be set. a new high to low transition indicating the start bit of a new fram e can come right after the last of the bits used for majorit y voting. for normal speed mode, the first low level sample can be at point marked (a) in figure 5-75 . for double speed mode the first low level must be delayed to (b). (c) marks a stop bit of full length. the early start bit detection influences the operational range of the receiver. 5.19.8.3 asynchronous operational range the operational range of the receiver is dependent on the mismatch between th e received bit rate and the internally generated baud rate. if the transmitter is sendi ng frames at too fast or too slow bit rates, or the internally generated baud r ate of the receiver does not have a similar (see table 5-70 on page 179 ) base frequency, the receiver will not be able to synchronize the frames to the start bit. the following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate. rxd sample (u2x = 0) sample (u2x = 1) bit n 1 2 3 4 5 6 7 8 1 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1 rxd sample (u2x = 0) sample (u2x = 1) stop 1 1 2 3 4 5 6 0/1 1 2 3 4 5 6 7 8 9 10 0/1 0/1 0/1 (a) (b) (c) r slow d 1 + () s s 1 ? ds ? s f ++ ------------------------------------------ = r fast d 2 + () s d 1 + () ss m + ----------------------------------- =
179 ata6614q [datasheet] 9240h?auto?10/14 d sum of character size and parity size (d = 5 to 10 bit) s samples per bit. s = 16 for normal speed mode and s = 8 for double speed mode. s f first sample number used for majority voting. s f = 8 for normal speed and s f = 4 for double speed mode. s m middle sample number used for majority voting. s m = 9 for normal speed and s m = 5 for double speed mode. r slow is the ratio of the slowest incoming data rate that ca n be accepted in relation to the receiver baud rate. r fast is the ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate. table 5-70 and table 5-71 list the maximum receiver baud rate error that c an be tolerated. note t hat normal speed mode has higher toleration of baud rate variations. the recommendations of the maximum receiver baud rate e rror was made under the assumption that the receiver and transmitter equally divides the maximum total error. there are two possible sources for the receivers baud rate erro r. the receiver?s system clo ck (xtal) will always have some minor instability over the supply voltage range and the temper ature range. when using a cryst al to generate the system clock, this is rarely a problem, but for a resonator the syst em clock may differ more than 2% depending of the resonators tolerance. the second source for the error is more controllable. the baud rate generator can not always do an exact division of the system frequency to get t he baud rate wanted. in this case an ubrrn value that give s an acceptable low error can be used if possible. 5.19.9 multi-processor communication mode setting the multi-processor communication mode (mpcmn) bit in ucsrna enables a filtering function of incoming frames received by the usart receiver. frames that do not contain address information will be ignored and not put into the receive buffer. this effectively reduces the number of incoming frames that has to be handled by the cpu, in a system with multiple mcus that communicate via the same serial bus. the transmitter is unaffected by the mpcmn setting, but has to be used differently when it is a part of a system ut ilizing the multi-proces sor communication mode. if the receiver is set up to receive fram es that contain 5 to 8 data bits, then the first stop bit indicates if the frame conta ins data or address information. if the receiver is set up for frames with nine data bits, then the ninth bit (rxb8n) is used for identifying address and data frames. when the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. when the frame type bit is zero the frame is a data frame. table 5-70. recommended maximum receiver baud rate error for normal speed mode (u2xn = 0) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 93.20 106.67 +6.67/-6.8 3.0 6 94.12 105.79 +5.79/-5.88 2.5 7 94.81 105.11 +5.11/-5.19 2.0 8 95.36 104.58 +4.58/-4.54 2.0 9 95.81 104.14 +4.14/-4.19 1.5 10 96.17 103.78 +3.78/-3.83 1.5 table 5-71. recommended maximum receiver baud rate error for double speed mode (u2xn = 1) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 94.12 105.66 +5.66/-5.88 2.5 6 94.92 104.92 +4.92/-5.08 2.0 7 95.52 104,35 +4.35/-4.48 1.5 8 96.00 103.90 +3.90/-4.00 1.5 9 96.39 103.53 +3.53/-3.61 1.5 10 96.70 103.23 +3.23/-3.30 1.0
ata6614q [datasheet] 9240h?auto?10/14 180 the multi-processor communication mode enables several slave m cus to receive data from a ma ster mcu. this is done by first decoding an address frame to find out which mcu has be en addressed. if a particular slave mcu has been addressed, it will receive the following data frames as normal, while the other slave mcus will ignore the received frames until another address frame is received. 5.19.9.1 using mpcmn for an mcu to act as a master mcu, it can use a 9-bit character frame format (ucszn = 7). the ninth bit (txb8n) must be set when an address frame (txb8n = 1) or cleared when a data fr ame (txb = 0) is being transmitted. the slave mcus must in this case be set to use a 9-bit character frame format. the following procedure should be used to exchange data in multi-processor communication mode: 1. all slave mcus are in multi-proc essor communication mode (mpcmn in ucsrna is set). 2. the master mcu sends an address frame, and all slaves receive and read this frame. in the slave mcus, the rxcn flag in ucsrna will be set as normal. 3. each slave mcu reads the udrn register and determines if it has been selected. if so, it clears the mpcmn bit in ucsrna, otherwise it waits for the next addr ess byte and keeps the mpcmn setting. 4. the addressed mcu will receive all data frames until a new address frame is received. the other slave mcus, which still have the mpcmn bit set, will ignore the data frames. 5. when the last data frame is received by the addre ssed mcu, the addressed mcu sets the mpcmn bit and waits for a new address frame from master. the process then repeats from 2. using any of the 5- to 8-bit character frame formats is possi ble, but impractical since the receiver must change between using n and n+1 character frame formats. this makes full-duplex operation difficult since the transmitter and receiver uses the same character size setting. if 5- to 8-bit character fr ames are used, the transmitter mu st be set to use two stop bit (usbsn = 1) since the firs t stop bit is used for indicating the frame type. do not use read-modify-write instructions (sbi and cbi) to se t or clear the mpcmn bit. the mpcmn bit shares the same i/o location as the txcn flag and this might accidental ly be cleared when using sbi or cbi instructions. 5.19.10 register description 5.19.10.1 udrn ? usart i/o data register n the usart transmit data buffer register an d usart receive data buffer registers share the same i/o address referred to as usart data register or udrn. the transmit data buffer regist er (txb) will be the destination for data written to the udrn register location. reading the udrn register location will return the contents of the receive data buffer register (rxb). for 5-, 6-, or 7-bit characters the upper unused bits will be ignored by the transmitter and set to zero by the receiver. the transmit buffer can only be written when the udren flag in the ucsrna regist er is set. data written to udrn when the udren flag is not set, will be ignored by the usart transmit ter. when data is written to the transmit buffer, and the transmitter is enabled, the transmitter will load the data into th e transmit shift register when th e shift register is empty. t hen the data will be serially transmitted on the txdn pin. the receive buffer consists of a two level fifo. the fifo will change its state whenever the re ceive buffer is accessed. due to this behavior of the receive buffer, do not use read-modify-write instructions (sbi and cbi) on this location. be careful when using bit test instructions (sbic and sbis), since these also will change the state of the fifo. bit 76543210 rxb[7:0] udrn (read) txb[7:0] udrn (write) read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
181 ata6614q [datasheet] 9240h?auto?10/14 5.19.10.2 ucsrna ? usart control and status register n a ? bit 7 ? rxcn: usart receive complete this flag bit is set when there are unread data in the rece ive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). if the receiver is disabled, the receive buffer will be flushed and consequently the rxcn bit wil l become zero. the rxcn flag can be used to generate a receiv e complete interrupt (see description of the rxcien bit). ? bit 6 ? txcn: usart transmit complete this flag bit is set when the entire frame in the transmit shi ft register has been shifted out and there are no new data curren tly present in the transmit buffer (udrn). th e txcn flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writin g a one to its bit location. the txcn flag c an generate a transmit complete interrupt (see description of the txcien bit). ? bit 5 ? udren: usart data register empty the udren flag indicates if the transmit buffer (udrn) is ready to receive new data. if udren is one, the buffer is empty, and therefore ready to be written. the udren flag can generat e a data register empty interrupt (see description of the udrien bit). udren is set after a reset to indicate that the transmitter is ready. ? bit 4 ? fen: frame error this bit is set if the next character in the receive buffer had a frame error when received. i.e. , when the first stop bit of t he next character in the receive buffer is zero . this bit is valid until the receive buff er (udrn) is read. the fen bit is zero wh en the stop bit of received data is one. alwa ys set this bit to zero when writing to ucsrna. ? bit 3 ? dorn: data overrun this bit is set if a data overrun conditi on is detected. a data overrun occurs when t he receive buffer is full (two characters) , it is a new character waiting in the receive shift register, and a new start bit is detected. this bit is valid until the recei ve buffer (udrn) is read. always set this bit to zero when writing to ucsrna. ? bit 2 ? upen: usart parity error this bit is set if the next character in the receive buffer had a parity error when received and the parity checking was enable d at that point (upmn1 = 1). this bit is valid until the receive bu ffer (udrn) is read. always set this bit to zero when writing to ucsrna. ? bit 1 ? u2xn: double the usart transmission speed this bit only has effect for the asyn chronous operation. write this bit to zero when using synchronous operation. writing this bit to one will reduce the divisor of the baud rate di vider from 16 to 8 effectively doubling the transfer rate fo r asynchronous communication. ? bit 0 ? mpcmn: multi-processor communication mode this bit enables the multi-processor communication mode. when the mpcmn bit is written to one, all the incoming frames received by the usart receiver that do not contain address information will be ignored. the tr ansmitter is unaffected by the mpcmn setting. for more detailed information see section 5.19.9 ?multi-processor communication mode? on page 179 . bit 76543210 rxcn txcn udren fen dorn upen u2xn mpcmn ucsrna read/write r r/w r r r r r/w r/w initial value00100000
ata6614q [datasheet] 9240h?auto?10/14 182 5.19.10.3 ucsrnb ? usart control and status register n b ? bit 7 ? rxcien: rx complete interrupt enable n writing this bit to one enables interrupt on the rxcn flag. a usart receive complete interrupt will be generated only if the rxcien bit is written to one, the global interrupt flag in sreg is written to one and the rxcn bit in ucsrna is set. ? bit 6 ? txcien: tx complete interrupt enable n writing this bit to one enables interrupt on the txcn flag. a u sart transmit complete interrupt will be generated only if the txcien bit is written to one, the global interrupt flag in sreg is written to one and the txcn bit in ucsrna is set. ? bit 5 ? udrien: usart data regi ster empty interrupt enable n writing this bit to one enables interrupt on the udren flag. a data register empty interrupt will be generated only if the udrien bit is written to one, the global interrupt flag in sreg is written to one and the udren bit in ucsrna is set. ? bit 4 ? rxenn: receiver enable n writing this bit to one enables the usart receiver. the receiv er will override normal port operation for the rxdn pin when enabled. disabling the receiver will flush the receiv e buffer invalidating the fen, dorn, and upen flags. ? bit 3 ? txenn: transmitter enable n writing this bit to one enables the usart transmitter. the tr ansmitter will override normal port operation for the txdn pin when enabled. the disabling of the transmitter (writing txenn to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the transmit shift regi ster and transmit buffer register do not contain data to be transmitted. when disabled, the transmitter will no longer override the txdn port. ? bit 2 ? ucszn2: character size n the ucszn2 bits combined with the ucszn1:0 bit in ucsrnc sets the number of data bits (character size) in a frame the receiver and transmitter use. ? bit 1 ? rxb8n: receive data bit 8 n rxb8n is the ninth data bit of the received character when ope rating with serial frames with nine data bits. must be read before reading the low bits from udrn. ? bit 0 ? txb8n: transmit data bit 8 n txb8n is the ninth data bit in the characte r to be transmitted when operating with seri al frames with nine data bits. must be written before writing the low bits to udrn. bit 76543210 rxcien txcien udrien rxenn txenn ucszn2 rxb8n txb8n ucsrnb read/write r/w r/w r/w r/w r/w r/w r r/w initial value 0 0 0 0 0 0 0 0
183 ata6614q [datasheet] 9240h?auto?10/14 5.19.10.4 ucsrnc ? usart control and status register n c ? bits 7:6 ? umseln1:0 usart mode select these bits select the mode of oper ation of the usartn as shown in table 5-72 . note: 1. see section 5.20 ?usart in spi mode? on page 187 for full description of the master spi mode (mspim) operation. ? bits 5:4 ? upmn1:0: parity mode these bits enable and set type of parity generation and c heck. if enabled, the transmitter will automatically generate and send the parity of the transmit ted data bits within each frame. the receiver will generate a parity value for the incoming data and compare it to the upmn setting. if a mismatch is detected, the upen flag in ucsrna will be set. ? bit 3 ? usbsn: stop bit select this bit selects the number of stop bits to be inserted by the transmitter. the receiver ignores this setting. ? bit 2:1 ? ucszn1:0: character size the ucszn1:0 bits combined with the ucszn2 bit in ucsrnb sets the number of data bits (character size) in a frame the receiver and transmitter use. bit 7 6 5 4 3 2 1 0 umseln1 umseln0 upmn1 upmn0 usbsn ucszn1 ucszn0 ucpoln ucsrnc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 1 1 0 table 5-72. umseln bits settings umseln1 umseln0 mode 0 0 asynchronous usart 0 1 synchronous usart 1 0 (reserved) 1 1 master spi (mspim) (1) table 5-73. upmn bits settings upmn1 upmn0 parity mode 0 0 disabled 0 1 reserved 1 0 enabled, even parity 1 1 enabled, odd parity table 5-74. usbs bit settings usbsn stop bit(s) 0 1-bit 1 2-bit
ata6614q [datasheet] 9240h?auto?10/14 184 ? bit 0 ? ucpoln: clock polarity this bit is used for synchronous mode only. write this bit to zero when asynchronous mode is used. the ucpoln bit sets the relationship between data output change and data input sample, and the synchronous clock (xckn). 5.19.10.5 ubrrnl and ubrrnh ? usart baud rate registers ? bit 15:12 ? reserved bits these bits are reserved for future use. for compatibility with future devices, these bit must be written to zero when ubrrnh is written. ? bit 11:0 ? ubrr11:0: usart baud rate register this is a 12-bit register which contains the usart baud rate. the ubrrnh contains the four most significant bits, and the ubrrnl contains the eight least signific ant bits of the usart baud rate. ongoin g transmissions by the transmitter and receiver will be corrupted if the baud rate is changed. writ ing ubrrnl will trigger an immediate update of the baud rate prescaler. 5.19.10.6 examples of baud rate setting for standard crystal and resonator freque ncies, the most commonly used baud ra tes for asynchronous operation can be generated by using the ubrrn settings in table 5-77 . ubrrn values which yield an actual baud rate differing less than 0.5% from the target baud rate, are bold in the table. higher error ratings are acceptable, but the receiver will have less noi se resistance when the error ratings are high, especially for large serial frames (see section 5.19.8.3 ?asynchronous operational range? on page 178 ). the error values are calculated using the following equation: table 5-75. ucszn bits settings ucszn2 ucszn1 ucszn0 character size 0 0 0 5-bit 0 0 1 6-bit 0 1 0 7-bit 0 1 1 8-bit 1 0 0 reserved 1 0 1 reserved 1 1 0 reserved 1 1 1 9-bit table 5-76. ucpoln bit settings ucpoln transmitted data changed (output of txdn pin) received data sampled (input on rxdn pin) 0 rising xckn edge falling xckn edge 1 falling xckn edge rising xckn edge bit 151413121110 9 8 ? ? ? ? ubrrn[11:8] ubrrnh ubrrn[7:0] ubrrnl 76543210 read/write rrrrr/wr/wr/wr/w r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000 00000000 error[%] baudrate closest match baudrate -------------------------------------------------- 1 ? ?? ?? 100% ? =
185 ata6614q [datasheet] 9240h?auto?10/14 table 5-77. examples of ubrrn settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 1.0000mhz f osc = 1.8432mhz f osc = 2.0000mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrrn error ubrrn error ubrrn error ubrrn error ubrrn error ubrrn error 2400 25 0.2% 51 0.2% 47 0.0% 95 0.0% 51 0.2% 103 0.2% 4800 12 0.2% 25 0.2% 23 0.0% 47 0.0% 25 0.2% 51 0.2% 9600 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 12 0.2% 25 0.2% 14.4k 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 19.2k 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 28.8k 1 8.5% 3 8.5% 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 38.4k 1 -18.6% 2 8.5% 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 57.6k 0 8.5% 1 8.5% 1 0.0% 3 0.0% 1 8.5% 3 8.5% 76.8k ? ? 1 -18.6% 1 -25.0% 2 0.0% 1 -18.6% 2 8.5% 115.2k ? ? 0 8.5% 0 0.0% 1 0.0% 0 8.5% 1 8.5% 230.4k ? ? ? ? ? ? 0 0.0% ? ? ? ? 250k ? ? ? ? ? ? ? ? ? ? 0 0.0% max. (1) 62.5kbps 125kbps 115.2kbps 230.4kbps 125kbps 250kbps notes: 1. ubrrn = 0, error = 0.0%. table 5-78. examples of ubrrn setti ngs for commonly used oscill ator frequencies (continued) baud rate (bps) f osc = 3.6864mhz f osc = 4.0000mhz f osc = 7.3728mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrrn error ubrrn error ubrrn error ubrrn error ubrrn error ubrrn error 2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0% 4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0% 9600 23 0.0% 47 0.0% 25 0.2% 51 0.2% 47 0.0% 95 0.0% 14.4k 15 0.0% 31 0.0% 16 2.1% 34 -0.8% 31 0.0% 63 0.0% 19.2k 11 0.0% 23 0.0% 12 0.2% 25 0.2% 23 0.0% 47 0.0% 28.8k 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 15 0.0% 31 0.0% 38.4k 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 57.6k 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 76.8k 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 115.2k 1 0.0% 3 0.0% 1 8.5% 3 8.5% 3 0.0% 7 0.0% 230.4k 0 0.0% 1 0.0% 0 8.5% 1 8.5% 1 0.0% 3 0.0% 250k 0 -7.8% 1 -7.8% 0 0.0% 1 0.0% 1 -7.8% 3 -7.8% 0.5m ? ? 0 -7.8% ? ? 0 0.0% 0 -7.8% 1 -7.8% 1m ? ? ? ? ? ? ? ? ? ? 0 -7.8% max. (1) 230.4kbps 460.8kbps 250kbps 0.5mbps 460.8kbps 921.6kbps note: 1. ubrrn = 0, error = 0.0%
ata6614q [datasheet] 9240h?auto?10/14 186 table 5-79. examples of ubrrn setti ngs for commonly used oscill ator frequencies (continued) baud rate (bps) f osc = 8.0000mhz f osc = 11.0592 mhz f osc = 14.7456mhz u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 u2xn = 0 u2xn = 1 ubrrn error ubrrn error ubrrn error ubrrn error ubrrn error ubrrn error 2400 207 0.2% 416 -0.1% 287 0.0% 575 0.0% 383 0.0% 767 0.0% 4800 103 0.2% 207 0.2% 143 0.0% 287 0.0% 191 0.0% 383 0.0% 9600 51 0.2% 103 0.2% 71 0.0% 143 0.0% 95 0.0% 191 0.0% 14.4k 34 -0.8% 68 0.6% 47 0.0% 95 0.0% 63 0.0% 127 0.0% 19.2k 25 0.2% 51 0.2% 35 0.0% 71 0.0% 47 0.0% 95 0.0% 28.8k 16 2.1% 34 -0.8% 23 0.0% 47 0.0% 31 0.0% 63 0.0% 38.4k 12 0.2% 25 0.2% 17 0.0% 35 0.0% 23 0.0% 47 0.0% 57.6k 8 -3.5% 16 2.1% 11 0.0% 23 0.0% 15 0.0% 31 0.0% 76.8k 6 -7.0% 12 0.2% 8 0.0% 17 0.0% 11 0.0% 23 0.0% 115.2k 3 8.5% 8 -3.5% 5 0.0% 11 0.0% 7 0.0% 15 0.0% 230.4k 1 8.5% 3 8.5% 2 0.0% 5 0.0% 3 0.0% 7 0.0% 250k 1 0.0% 3 0.0% 2 -7.8% 5 -7.8% 3 -7.8% 6 5.3% 0.5m 0 0.0% 1 0.0% ? ? 2 -7.8% 1 -7.8% 3 -7.8% 1m ? ? 0 0.0% ? ? ? ? 0 -7.8% 1 -7.8% max .(1) 0.5mbps 1mbps 691.2kbps 1.3824mbps 921.6kbps 1.8432mbps note: 1. ubrrn = 0, error = 0.0% table 5-80. examples of ubrrn setti ngs for commonly used oscill ator frequencies (continued) baud rate (bps) f osc = 16.0000mhz u2xn = 0 u2xn = 1 ubrrn error ubrrn error 2400 416 -0.1% 832 0.0% 4800 207 0.2% 416 -0.1% 9600 103 0.2% 207 0.2% 14.4k 68 0.6% 138 -0.1% 19.2k 51 0.2% 103 0.2% 28.8k 34 -0.8% 68 0.6% 38.4k 25 0.2% 51 0.2% 57.6k 16 2.1% 34 -0.8% 76.8k 12 0.2% 25 0.2% 115.2k 8 -3.5% 16 2.1% 230.4k 3 8.5% 8 -3.5% 250k 3 0.0% 7 0.0% 0.5m 1 0.0% 3 0.0% 1m 0 0.0% 1 0.0% max. (1) 1mbps 2mbps note: 1. ubrrn = 0, error = 0.0%
187 ata6614q [datasheet] 9240h?auto?10/14 5.20 usart in spi mode 5.20.1 features full duplex, three-wire synchronous data transfer master operation supports all four spi modes of operation (mode 0, 1, 2, and 3) lsb first or msb first data transfer (configurable data order) queued operation (double buffered) high resolution baud rate generator high speed operation (f xckmax = f ck /2) flexible interrupt generation 5.20.2 overview the universal synchronous and asynchronous serial receiver a nd transmitter (usart) can be set to a master spi compliant mode of operation. setting both umseln1:0 bits to one enables the usart in mspi m logic. in this mode of operation the spi master control logic takes direct control over the usart resources. these resources include th e transmitter and receiver shift register and buffers, and the baud rate generator. the parity generator and checker, the data and clock recovery logic, and the rx and tx control logic is disabled. the usart rx and tx control logic is replaced by a common spi transf er control logic. however, the pin control logic and interrupt generat ion logic is identical in both modes of operation. the i/o register locations are the same in both modes. however, some of the functionality of the control registers changes when using mspim. 5.20.3 clock generation the clock generation logic generates the base clock for the transmitter and receiver. for usart mspim mode of operation only internal clock generation (i.e. master operation) is suppor ted. the data direction register for the xckn pin (ddr_xckn) must therefore be set to one (i.e. as output) for the usart in mspim to operate correctly. preferably the ddr_xckn should be set up before the usart in mspim is enabled (i.e. txenn and rxenn bit set to one). the internal clock generation used in mspim mode is identica l to the usart synchronous master mode. the baud rate or ubrrn setting can therefore be calcul ated using the same equations, see table 5-81 : table 5-81. equations for calculat ing baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrrn value synchronous master mode note: 1. the baud rate is defined to be the transfer rate in bit per second (bps) baud baud rate (in bits per second, bps) f osc system oscillator clock frequency ubrrn contents of the ubrrnh and ubrrnl registers, (0-4095) baud f osc 2 ubrr n 1 + () ------------------------------------- - = ubrr n f osc 2 baud ------------------- - 1 ? =
ata6614q [datasheet] 9240h?auto?10/14 188 5.20.4 spi data modes and timing there are four combinations of xckn (s ck) phase and polarity with respect to serial data, which are determined by control bits ucphan and ucpoln. the data transfer timing diagrams are shown in figure 5-76 . data bits are shifted out and latched in on opposite edges of the xckn signal, ensuring sufficient time for data signals to stabilize. the ucpoln and ucphan functionality is summarized in table 5-82 . note that changing the setting of any of these bits will corrupt all ongoing communication for both the receiver and transmitter. figure 5-76. ucphan and ucpoln data transfer timing diagrams 5.20.5 frame formats a serial frame for the mspim is defined to be one character of 8 data bits. the usart in mspim mode has two valid frame formats: 8-bit data with msb first 8-bit data with lsb first a frame starts with the least or most significant data bit. then the next data bits, up to a total of eight, are succeeding, en ding with the most or least significant bit accordingly. when a comple te frame is transmitted, a new frame can directly follow it, o r the communication line can be set to an idle (high) state. the udordn bit in ucsrnc sets the frame format used by the usart in mspim mode. the receiver and transmitter use the same setting. note that changing t he setting of any of these bits will corr upt all ongoing communication for both the receiver and transmitter. 16-bit data transfer can be achieved by wr iting two data bytes to udrn. a uart transmit complete interrupt will then signal that the 16-bit value has been shifted out. table 5-82. ucpoln and ucphan functionality- ucpoln ucphan spi mode leading edge trailing edge 0 0 0 sample (rising) setup (falling) 0 1 1 setup (rising) sample (falling) 1 0 2 sample (falling) setup (rising) 1 1 3 setup (falling) sample (rising) xck ucpol = 0 ucpol = 1 ucpha = 1 ucpha = 0 data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd) xck data setup (txd) data sample (rxd)
189 ata6614q [datasheet] 9240h?auto?10/14 5.20.5.1 usart mspim initialization the usart in mspim mode has to be initialized before any communication can take place. the initialization process normally consists of setting the baud ra te, setting master mode of operation (by setting ddr_xckn to one), setting frame format and enabling the transmitter and the receiver. only t he transmitter can operate independently. for interrupt driven usart operation, the global interrupt flag should be cleared (and thus interrupts globally disabled) when doing the initialization. note: to ensure immediate initialization of the xckn output th e baud-rate register (ubrrn) must be zero at the time the transmitter is enabled. contrary to the normal mode usart operation the ubrrn must then be written to the desired value after the transmitter is enabled, but bef ore the first transmission is started. setting ubrrn to zero before enabling the transmitter is not necessary if th e initialization is done immediately after a reset since ubrrn is reset to zero. before doing a re-initialization with changed baud rate, data mode, or frame format, be sure that there is no ongoing transmissions during the period the regist ers are changed. the txcn flag can be us ed to check that the transmitter has completed all transfers, and the rxcn flag can be used to che ck that there are no unread data in the receive buffer. note that the txcn flag must be cleared before each transmission (before udrn is written) if it is used for this purpose. the following simple usart initialization code examples sh ow one assembly and one c function that are equal in functionality. the examples assume polling (no interrupts enabled). the baud rate is given as a function parameter. for the assembly code, the baud rate parameter is assu med to be stored in the r17:r16 registers. note: 1. see section 5.5 ?about code examples? on page 32 . assembly code example (1) usart_init: clr r18 out ubrrnh,r18 out ubrrnl,r18 ; setting the xckn port pin as output, enables master mode. sbi xckn_ddr, xckn ; set mspi mode of operation and spi data mode 0. ldi r18, (1< ata6614q [datasheet] 9240h?auto?10/14 190 5.20.6 data transfer using the usart in mspi mode requires the transmitter to be e nabled, i.e. the txenn bit in the ucsrnb register is set to one. when the transmitter is enabled, the normal port operation of the txdn pin is overridden and given the function as the transmitter's serial output. enabling the receiver is optional a nd is done by setting the rxenn bit in the ucsrnb register to one. when the receiver is enabled, the normal pin operation of the rxdn pin is overridden and given the function as the receiver's serial input. the xckn will in both cases be used as the transfer clock. after initialization the usart is ready for doing data transfers. a data transfer is initiated by writing to the udrn i/o locat ion. this is the case for both sending and receiving data since the transmitter controls the transfer clock. the data written to udrn is moved from the transmit buffer to the shift register when the shift register is ready to send a new frame. note: to keep the input buffer in sync with the number of data bytes transmitted, the udrn register must be read once for each byte transmitted. the input buffer operatio n is identical to normal usart mode, i.e. if an over- flow occurs the character last received will be lost, not th e first data in the buffer. this means that if four bytes are transferred, byte 1 first, then by te 2, 3, and 4, and the udrn is not read before all transfers are completed, then byte 3 to be received will be lost, and not byte 1. the following code examples show a simple usart in mspim mo de transfer function based on polling of the data register empty (udren) flag and the receive complete (rxcn) flag. the u sart has to be initialized before the function can be used. for the assembly code, the data to be sent is assumed to be st ored in register r16 and the data received will be available in the same register (r16) af ter the function returns. the function simply waits for the transmit buffer to be empty by checking the udren flag, before loading it with new data to be transmitted. the function then waits for data to be present in the receive buffer by checking the rxcn flag, before reading the buffer and returning the value. note: 1. see section 5.5 ?about code examples? on page 32 . assembly code example (1) usart_mspim_transfer: ; wait for empty transmit buffer sbis ucsrna, udren rjmp usart_mspim_transfer ; put data (r16) into buffer, sends the data out udrn,r16 ; wait for data to be received usart_mspim_wait_rxcn: sbis ucsrna, rxcn rjmp usart_mspim_wait_rxcn ; get and return received data from buffer in r16, udrn ret c code example (1) unsigned char usart_receive( void ) { /* wait for empty transmit buffer */ while (!(ucsrna & (1< 191 ata6614q [datasheet] 9240h?auto?10/14 5.20.6.1 transmitter and receiver flags and interrupts the rxcn, txcn, and udren flags and corresponding interrupts in usart in mspim mode are identical in function to the normal usart operation. however, the rece iver error status flags (fe, dor, and pe) are not in use and is always read as zero. 5.20.6.2 disabling the transmitter or receiver the disabling of the transmitter or receiver in usart in mspi m mode is identical in function to the normal usart operation. 5.20.7 avr usart m spim versus avr spi the usart in mspim mode is fully compatible with the avr ? spi regarding: master mode timing diagram. the ucpoln bit functionality is identical to the spi cpol bit. the ucphan bit functionality is identical to the spi cpha bit. the udordn bit functionality is identical to the spi dord bit. however, since the usart in mspim mode reuses the usar t resources, the use of the usart in mspim mode is somewhat different compared to the spi. in addition to differenc es of the control register bits, and that only master operation is supported by the usart in mspim mode, the fo llowing features differ between the two modules: the usart in mspim mode includes (double) buffer ing of the transmitter. the spi has no buffer. the usart in mspim mode receiver includes an additional buffer level. the spi wcol (write collision) bit is not included in usart in mspim mode. the spi double speed mode (spi2x) bit is not included. howe ver, the same effect is achieved by setting ubrrn accordingly. interrupt timing is not compatible. pin control differs due to the master on ly operation of the usart in mspim mode. a comparison of the usart in mspim mode and the spi pins is shown in table 5-83 . 5.20.8 register description the following section describes the regist ers used for spi operation using the usart. 5.20.8.1 udrn ? usart ms pim i/o data register the function and bit description of the usart data register (udrn) in mspi mode is identical to normal usart operation. see section 5.19.10.1 ?udrn ? usart i/o data register n? on page 180 . table 5-83. comparison of usart in mspim mode and spi pins usart_mspim spi comment txdn mosi master out only rxdn miso master in only xckn sck (functionally identical) (n/a) ss not supported by usart in mspim
ata6614q [datasheet] 9240h?auto?10/14 192 5.20.8.2 ucsrna ? usart mspim control and status register n a ? bit 7 - rxcn: usart receive complete this flag bit is set when there are unread data in the rece ive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). if the receiver is disabled, the receive buffer will be flushed and consequently the rxcn bit wil l become zero. the rxcn flag can be used to generate a receiv e complete interrupt (see description of the rxcien bit). ? bit 6 - txcn: usart transmit complete this flag bit is set when the entire frame in the transmit shi ft register has been shifted out and there are no new data curren tly present in the transmit buffer (udrn). th e txcn flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writin g a one to its bit location. the txcn flag c an generate a transmit complete interrupt (see description of the txcien bit). ? bit 5 - udren: usart data register empty the udren flag indicates if the transmit buffer (udrn) is ready to receive new data. if udren is one, the buffer is empty, and therefore ready to be written. the udren flag can generat e a data register empty interrupt (see description of the udrie bit). udren is set after a reset to in dicate that the transmitter is ready. ? bit 4:0 - reserved bits in mspi mode when in mspi mode, these bits are reserved for future use. fo r compatibility with future devices, these bits must be written to zero when ucsrna is written. 5.20.8.3 ucsrnb ? usart mspim control and status register n b ? bit 7 - rxcien: rx complete interrupt enable writing this bit to one enables interrupt on the rxcn flag. a usart receive complete interrupt will be generated only if the rxcien bit is written to one, the global interrupt flag in sreg is written to one and the rxcn bit in ucsrna is set. ? bit 6 - txcien: tx co mplete interrupt enable writing this bit to one enables interrupt on the txcn flag. a u sart transmit complete interrupt will be generated only if the txcien bit is written to one, the global interrupt flag in sreg is written to one and the txcn bit in ucsrna is set. ? bit 5 - udrie: usart data re gister empty interrupt enable writing this bit to one enables interrupt on the udren flag. a data register empty interrupt will be generated only if the udrie bit is written to one, the global interrupt flag in sr eg is written to one and the udren bit in ucsrna is set. ? bit 4 - rxenn: receiver enable writing this bit to one enables the usart receiver in mspim mode. the receiver will override normal port operation for the rxdn pin when enabled. disabling the receiver will flush the rece ive buffer. only enabling the receiver in mspi mode (i.e. setting rxenn=1 and txenn=0) has no meaning since it is the transmitter that controls the transfer clock and since only master mode is supported. bit 7 6 5 4 3 2 1 0 rxcn txcn udren - - - - - ucsrna read/write r r/w r r r r r r initial value 0 0 0 0 0 1 1 0 bit 7 6 5 4 3 2 1 0 rxcien txcien udrie rxenn txenn - - - ucsrnb read/write r/w r/w r/w r/w r/w r r r initial value 0 0 0 0 0 1 1 0
193 ata6614q [datasheet] 9240h?auto?10/14 ? bit 3 - txenn: transmitter enable writing this bit to one enables the usart transmitter. the tr ansmitter will override normal port operation for the txdn pin when enabled. the disabling of the transmitter (writing txenn to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the transmit shift regi ster and transmit buffer register do not contain data to be transmitted. when disabled, the transmitter will no longer override the txdn port. ? bit 2:0 - reserved bits in mspi mode when in mspi mode, these bits are reserved for future use. fo r compatibility with future devices, these bits must be written to zero when ucsrnb is written. 5.20.8.4 ucsrnc ? usart mspim control and status register n c ? bit 7:6 - umseln1:0: usart mode select these bits select the mode of operation of the usart as shown in table 5-84 . see section 5.19.10.4 ?ucsrnc ? usart control and status register n c? on page 183 for full description of the normal usart operation. the mspim is enabled when both umseln bits are set to one. the udordn, ucphan, a nd ucpoln can be set in the same write operation where the mspim is enabled. ? bit 5:3 - reserved bits in mspi mode when in mspi mode, these bits are reserved for future use. fo r compatibility with future devices, these bits must be written to zero when ucsrnc is written. ? bit 2 - udordn: data order when set to one the lsb of the data word is transmitted first. when set to zero the msb of the data word is transmitted first. refer to the frame formats section page 4 for details. ? bit 1 - ucphan: clock phase the ucphan bit setting determine if data is sampled on the leas ing edge (first) or tailing (last) edge of xckn. refer to the spi data modes and timing section page 4 for details. ? bit 0 - ucpoln: clock polarity the ucpoln bit sets the polarity of the xckn clock. the combination of the ucpoln and ucphan bit settings determine the timing of the data transfer. refer to the spi data modes and timing section page 4 for details. 5.20.8.5 usart mspim baud rate registers - ubrrnl and ubrrnh the function and bit description of the baud rate registers in mspi mode is i dentical to normal usart operation, see section 5.19.10.5 ?ubrrnl and ubrrnh ? usart b aud rate registers? on page 184 . bit 7 6 543 2 1 0 umseln1 umseln0 - - - udordn ucphan ucpoln ucsrnc read/write r/w r/w r r r r/w r/w r/w initial value 0 0 0 0 0 1 1 0 table 5-84. umseln bits settings umseln1 umseln0 mode 0 0 asynchronous usart 0 1 synchronous usart 1 0 reserved 1 1 master spi (mspim)
ata6614q [datasheet] 9240h?auto?10/14 194 5.21 2-wire serial interface 5.21.1 features simple yet powerful and flexible communication interface, only two bus lines needed both master and slave operation supported device can operate as transmitter or receiver 7-bit address space allows up to 128 different slave addresses multi-master arbitration support up to 400khz data transfer speed slew-rate limited output drivers noise suppression circuitry rejects spikes on bus lines fully programmable slave address with general call support address recognition causes wake-up when avr ? is in sleep mode compatible with philips? i 2 c protocol 5.21.2 2-wire serial interface bus definition the 2-wire serial interface (twi) is ideally suited for typica l microcontroller applications. the twi protocol allows the systems designer to interconnect up to 128 different devices using only two bi-directional bus lines, one for clock (scl) and one for data (sda). the only external hardware needed to implem ent the bus is a single pull-up re sistor for each of the twi bus lines. all devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the twi protocol. figure 5-77. twi bus interconnection device 1 sda scl v cc device 2 device 3 device n ........ r1 r2
195 ata6614q [datasheet] 9240h?auto?10/14 5.21.2.1 twi terminology the following definitions are frequently encountered in this section. the prtwi bit in section 5.9.10 ?minimizing powe r consumption? on page 60 must be written to zero to enable the 2-wire serial interface. 5.21.2.2 electrical interconnection as depicted in figure 5-77 , both bus lines are connected to the positive su pply voltage through pull-up resistors. the bus drivers of all twi-compliant devices are open-drain or open- collector. this implements a wired-and function which is essential to the operation of the interface. a low level on a twi bus line is generated when one or more twi devices output a zero. a high level is output when all twi devices tri-state t heir outputs, allowing the pull-up resistors to pull the line hi gh. note that all avr ? devices connected to the twi bus must be powered in order to allow any bus operation. the number of devices that can be connecte d to the bus is only limited by the bus capacitance limit of 400pf and the 7-bit slave address space. a detailed specification of the electrical characteristics of the twi is given in section 5.28.7 ?2-wire serial interface characteristics? on page 283 . two different sets of specifications ar e presented there, o ne relevant for bus speeds below 100 khz, and one valid for bus speeds up to 400khz. 5.21.3 data transfer and frame format 5.21.3.1 transferring bits each data bit transferred on the twi bus is accompanied by a pulse on the clock line. the level of the data line must be stable when the clock line is high. the only exception to this rule is for generat ing start and stop conditions. figure 5-78. data validity table 5-85. twi terminology term description master the device that initiates and terminates a transmission. the master also generates the scl clock. slave the device addressed by a master. transmitter the device placing data on the bus. receiver the device reading data from the bus. sda scl data stable data change data stable
ata6614q [datasheet] 9240h?auto?10/14 196 5.21.3.2 start and stop conditions the master initiates and terminates a data transmission. the transmission is in itiated when the master issues a start condition on the bus, and it is termina ted when the master issues a stop condition. between a start and a stop condition, the bus is considered busy, and no other master should try to seize control of the bus. a special case occurs when a new start condition is issued between a start and stop condition. this is referred to as a repeated start condition, and is used when the master wi shes to initiate a new transfer without relinquishing control of the bus. after a repeated start, the bus is considered bu sy until the next stop. this is identic al to the start behavior, and therefore start is used to describe both start and repeated start for the remainder of this datasheet, unl ess otherwise noted. as depicted below, start and stop conditions are signa lled by changing the level of the sda line when the scl line is high. figure 5-79. start, repeated start and stop conditions 5.21.3.3 address packet format all address packets transmitted on the twi bus are 9 bits long , consisting of 7 address bits, one read/write control bit and an acknowledge bit. if the read/write bit is set, a re ad operation is to be performe d, otherwise a write operation should be performed. when a slave recognizes that it is being addressed, it should acknowledge by pulling sda low in the ninth scl (ack) cycle. if the addressed slave is busy, or for some other reason can not service the master?s request, the sda line should be left high in the ack clock cycle. the master can then tran smit a stop condition, or a repeated start condition to initiate a new transmission. an address packet consisting of a slave address and a read or a write bit is called sla+r or sla+w, respectively. the msb of the address byte is transmitted first. slave addres ses can freely be allocated by the designer, but the address 0000 000 is reserved for a general call. when a general call is issued, all slaves should respond by pulling the sda line low in the ack cycle. a general call is used when a master wishes to transmit the same message to several slaves in th e system. when the gener al call address followed by a write bit is transmitted on the bus, all slaves set up to acknowledge the general call will pull the sda line low in the ack cycle. the following data packets will then be received by all the slaves that acknowledged the general call. note that transmitting the general call address followed by a read bit is meaningless, as this would cause contention if several slaves started transmitting different data. all addresses of the format 1111 xxx shou ld be reserved for future purposes. figure 5-80. address packet format sda scl start start repeated start stop stop sda scl start addr msb addr lsb r/w ack 12 789
197 ata6614q [datasheet] 9240h?auto?10/14 5.21.3.4 data packet format all data packets transmitted on the twi bus are nine bits long , consisting of one data byte and an acknowledge bit. during a data transfer, the master generat es the clock and the start and stop conditions, while the receiver is responsible for acknowledging the reception. an acknowledge (ack) is signal led by the receiver pulling the sda line low during the ninth scl cycle. if the receiver leaves the sda line high, a nack is signalled. when the receiver has received the last byte, or for some reason cannot receive any more bytes, it should info rm the transmitter by sending a nack after the final byte. the msb of the data byte is transmitted first. figure 5-81. data packet format 5.21.3.5 combining address and data packets into a transmission a transmission basically consists of a start condition, a sla+ r/w, one or more data packets and a stop condition. an empty message, consisting of a start follo wed by a stop condition, is illegal. note that the wired-anding of the scl line can be used to implement handshaking betw een the master and the slave. the sl ave can extend the scl low period by pulling the scl line low. this is useful if the clock speed set up by the master is too fast fo r the slave, or the slave needs extra time for processing between the data transmissions. t he slave extending the scl low pe riod will not affect the scl high period, which is determined by the master. as a consequ ence, the slave can reduce th e twi data transfer speed by prolonging the scl duty cycle. figure 5-82 shows a typical data transmission. note that severa l data bytes can be transmitted between the sla+r/w and the stop condition, depending on the software prot ocol implemented by the application software. figure 5-82. typical data transmission aggregate sda sda from transmitter sda from receiver scl from master data msb data lsb ack 12 7 data byte stop, repeated start or next data byte sla + r/w 89 sda scl start sla + r/w data byte stop addr msb addr lsb data msb data lsb ack r/w ack 12 789 12 789
ata6614q [datasheet] 9240h?auto?10/14 198 5.21.4 multi-master bus systems, arbitration and synchronization the twi protocol al lows bus systems with several mast ers. special concerns have been taken in order to ensure that transmissions will proceed as normal, even if two or more mast ers initiate a transmission at the same time. two problems arise in multi-master systems: an algorithm must be implemented allowing only one of t he masters to complete the transmission. all other masters should cease transmission when they disco ver that they have lost the selecti on process. this selection process is called arbitration. when a contending master discovers that it has lost the arbi tration process, it should immediately switch to slave mode to check whether it is being addre ssed by the winning master. the fact that multiple masters have started transmission at the same time should not be det ectable to the slaves, i.e. the data being transferred on the bus must not be corrupted. different masters may use different sc l frequencies. a scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashi on. this will facilit ate the arbitration process. the wired-anding of the bus lines is used to solve both these problems. the seri al clocks from all masters will be wired- anded, yielding a combined clock with a high period equal to the one from the master with the shortest high period. the low period of the combined clock is equal to the low period of the master with the longest low period. note that all masters listen to the scl line, effectively starting to count their scl high a nd low time-out periods when the combined scl line goes high or low, respectively. figure 5-83. scl synchronization between multiple masters arbitration is carried out by all masters continuously monitori ng the sda line after outputting data. if the value read from th e sda line does not match the value the master had output, it has lost the arbitration. note that a master can only lose arbitration when it outputs a high sda va lue while another master outputs a low value. the losing master should immediately go to slave mode, checking if it is being addressed by the winning master. the sda line should be left high, but losing masters are allowed to generate a clock signal until the end of the curr ent data or address packet. arbitration will continue until only one mast er remains, and this may take many bits . if several masters are trying to address the same slave, arbitration will continue into the data packet. scl from master a scl from master b scl bus line masters start counting low period masters start counting high period ta low ta high tb low tb high
199 ata6614q [datasheet] 9240h?auto?10/14 figure 5-84. arbitration between two masters note that arbitration is not allowed between: a repeated start condition and a data bit. a stop condition and a data bit. a repeated start and a stop condition. it is the user software?s responsibility to ensure that these illegal arbitration cond itions never occur. this implies that in multi- master systems, all data transfers must use the same com position of sla+r/w and data pa ckets. in other words: all transmissions must contain the same number of data packets , otherwise the result of t he arbitration is undefined. sda from master a sda from master b synchronized scl line sda line start master a loses arbitration, sda a sda
ata6614q [datasheet] 9240h?auto?10/14 200 5.21.5 overview of the twi module the twi module is comprised of several submodules, as shown in figure 5-85 . all registers drawn in a thick line are accessible through the avr ? data bus. figure 5-85. overview of the twi module 5.21.5.1 scl and sda pins these pins interface the avr twi with the rest of the mcu system. the output drivers contain a slew-rate limiter in order to conform to the twi specification. the inpu t stages contain a spike suppression unit removing spikes shorter than 50ns. note that the internal pull-ups in the avr p ads can be enabled by setting the port bits corresponding to the scl and sda pins, as explained in the i/o port section. the internal pull-ups can in some systems eliminate the need for external ones. 5.21.5.2 bit rate generator unit this unit controls the period of scl when operating in a master mode. the scl period is controlled by settings in the twi bit rate register (twbr) and the prescaler bits in the twi status register (twsr). slave operation does not depend on bit rate or prescaler settings, but the cpu clock frequency in the slave must be at least 16 times higher than the scl frequency. note that slaves may prolong the scl lo w period, thereby reducing the average tw i bus clock period. the scl frequency is generated according to the following equation: twbr = value of the twi bit rate register. prescalervalue = value of the prescaler, see table 5-92 on page 221 . note: pull-up resistor values should be selected according to the scl frequency and the capacitive bus line load. see table 5-134 on page 283 for value of pull-up resistor. start/ stop control spike filter slew-rate control address/ data shift register (twdr) arbitration detection spike suppression bit rate register (twbr) prescaler ack bus interface unit scl spike filter slew-rate control sda bit rate generator address register (twar) address comparator address match unit status register (twsr) control register (twcr) state machine and status control control unit twi unit scl frequency cpu clock frequency 16 2(twbr) prescalervalue () ? + --------------------------------------------------------------------------------------- - =
201 ata6614q [datasheet] 9240h?auto?10/14 5.21.5.3 bus interface unit this unit contains the data and address shift register (twdr) , a start/stop controller and arbitration detection hardware. the twdr contains the address or data bytes to be transmitted, or the address or data bytes received. in addition to the 8- bit twdr, the bus interface unit also cont ains a register containing the (n)ack bit to be transmitted or received. this (n)ack register is not directly accessible by the application so ftware. however, when receiving, it can be set or cleared by manipulating the twi control register (twcr). when in trans mitter mode, the value of the received (n)ack bit can be determined by the value in the twsr. the start/stop controller is responsible for generati on and detection of start, repeated start, and stop conditions. the start/stop controller is able to detect start and stop conditions even when the avr ? mcu is in one of the sleep modes, enabling the mcu to wake up if addressed by a master. if the twi has initiated a transmission as master, the arbitrat ion detection hardware continuous ly monitors the transmission trying to determine if arbitration is in process. if the twi has lost an arbitration, the control un it is informed. correct act ion can then be taken and appropr iate status codes generated. 5.21.5.4 address match unit the address match unit checks if received address bytes match the seven-bit addre ss in the twi address register (twar). if the twi general call recognition enable (twgce) bit in the tw ar is written to one, all incoming address bits will also be compared against the general call address. upon an address matc h, the control unit is informed, allowing correct action to be taken. the twi may or may not acknowledge its address, dep ending on settings in the twcr. the address match unit is able to compare addresses even when the avr mcu is in sleep mode, enabling the mcu to wake up if addressed by a master. if another interrupt (e.g., int0) occurs during twi power-down address match and wakes up the cpu, the twi aborts operation and return to it?s idle state. if this cause any problems, ensure that twi address match is the only enabled interrup t when entering power-down. 5.21.5.5 control unit the control unit monitors the twi bus and generates responses corresponding to settings in the twi control register (twcr). when an event requiring the attention of the applicat ion occurs on the twi bus, the twi interrupt flag (twint) is asserted. in the next clock cycle, the twi status register (twsr) is updated with a status code identifying the event. the twsr only contains relevant status information when the tw i interrupt flag is asserted. at all other times, the twsr contains a special status code indicating that no relevant status inform ation is available. as long as the twint flag is set, t he scl line is held low. this allows the application software to co mplete its tasks before allo wing the twi transmission to continue. the twint flag is set in the following situations: after the twi has transmitted a start/repeated start condition. after the twi has transmitted sla+r/w. after the twi has transmitted an address byte. after the twi has lost arbitration. after the twi has been addressed by own slave address or general call. after the twi has received a data byte. after a stop or repeated start has been received while still addressed as a slave. when a bus error has occurred due to an illegal start or stop condition. 5.21.6 using the twi the avr twi is byte-oriented and interrupt based. interrupts are issued after all bus events, like reception of a byte or transmission of a start condition. because the twi is interr upt-based, the applicat ion software is free to carry on other operations during a twi byte transfer. note that the twi inte rrupt enable (twie) bit in twcr together with the global interrupt enable bit in sreg allow the application to decide wh ether or not assertion of the twint flag should generate an interrupt request. if the twie bit is cleared, the application mu st poll the twint flag in order to detect actions on the twi bus. when the twint flag is asserted, the twi has finished an operati on and awaits application response. in this case, the twi status register (twsr) contains a value indicating the curr ent state of the twi bus. the application software can then decide how the twi should behave in the next twi bus cycle by m anipulating th e twcr and twdr registers.
ata6614q [datasheet] 9240h?auto?10/14 202 figure 5-86 is a simple example of how the application can interfac e to the twi hardware. in this example, a master wishes to transmit a single data byte to a slave. this description is quite abstract, a more detailed explanation follows later in thi s section. a simple code example implementi ng the desired behavior is also presented. figure 5-86. interfacing the application to the twi in a typical transmission 1. the first step in a twi transmission is to transmit a star t condition. this is done by writing a specific value into twcr, instructing the twi hardware to transmit a start condition. which value to write is described later on. however, it is important that the twin t bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as l ong as the twint bit in twcr is set. immediately after the application has cleared twint, the twi will initiate transmission of the start condition. 2. when the start condition has been transmitted, the twin t flag in twcr is set, and twsr is updated with a status code indicating that the star t condition has successfully been sent. 3. the application software should now examine the value of twsr, to make sure that the start condition was successfully transmitted. if twsr indicates otherwise, the application software might take some special action, like calling an error routine. assuming that the status co de is as expected, the applic ation must load sla+w into twdr. remember that twdr is used both for address a nd data. after twdr has been loaded with the desired sla+w, a specific value must be written to twcr, instru cting the twi hardware to transmit the sla+w present in twdr. which value to write is described later on. however, it is important that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any o peration as long as the twint bit in twcr is set. immediately after the application has cleared twint, the tw i will initiate transmission of the address packet. 4. when the address packet has been transmitted, the twin t flag in twcr is set, and twsr is updated with a status code indicating that the address packet has su ccessfully been sent. the status code will also reflect whether a slave acknowledged the packet or not. 5. the application software should now examine the value of twsr, to make sure that the address packet was suc- cessfully transmitted, and that the value of the ack bit was as expected. if twsr indicates otherwise, the application software might take some special action, like ca lling an error routine. assu ming that the status code is as expected, the application mu st load a data packet into twdr. subsequen tly, a specific valu e must be written to twcr, instructing the twi hardware to transmit the data packet present in twdr. which value to write is described later on. however, it is important that the twin t bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as l ong as the twint bit in twcr is set. immediately after the application has cleared twint, the twi will initiate transmission of the data packet. 6. when the data packet has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the data packet has successfully been sent. the status code will also reflect whether a slave acknowledged the packet or not. start twi hardware action application action twi bus indicates twint set sla + w a a stop data 1. application writes to twcr to initiate transmission of start 2. twint set. status code indicates start condition sent 4. twint set. status code indicates sla + w sent, ack received 6. twint set. status code indicates data sent, ack received 3. check twsr to see if start was sent. application loads sla + w into twdr, and loads appropriate control signals into twcr, makin sure that twint is written to one, and twsta is written to zero. 5. check twsr to see if sla + w was sent and ack received. application loads data intotwdr, and loads appropriate control signals into twcr, makin sure that twint is written to one 7. check twsr to see if data was sent and ack received. application loads appropriate control signals to send stop into twcr, makin sure that twint is written to one
203 ata6614q [datasheet] 9240h?auto?10/14 7. the application software should now examine the value of twsr, to make sure that the data packet was success- fully transmitted, and that t he value of the ack bit was as expected. if twsr indicates otherwise, the application software might take some special action, like calling an error routine. assuming that the status code is as expected, the application must write a specific value to twcr, instru cting the twi hardware to transmit a stop condition. which value to write is described later on. howeve r, it is important that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any o peration as long as the twint bit in twcr is set. immediately after the app lication has cleared twint, the twi will initiate transmission of the stop condition. note that twint is not set after a stop condition has been sent. even though this example is simple, it show s the principles involved in all twi transmissions. these can be summarized as follows: when the twi has finished an operation and expects application response, the twint flag is set. the scl line is pulled low until twint is cleared. when the twint flag is set, the user mu st update all twi r egisters with the va lue relevant for t he next twi bus cycle. as an example, twdr must be lo aded with the value to be tran smitted in the next bus cycle. after all twi register updates and other pending applicat ion software tasks have been completed, twcr is written. when writing twcr, the twint bit should be set. writ ing a one to twint clears the flag. the twi will then commence executing whatever operatio n was specified by the twcr setting. in table 5-86 an assembly and c implementation of the example is given. note that the code below assumes that several definitions have been made, for ex ample by using include-files. table 5-86. assembly and c implementation assembly code example c example comments 1 ldi r16, (1< ata6614q [datasheet] 9240h?auto?10/14 204 5.21.7 transmission modes the twi can operate in one of four major modes. these are na med master transmitter (mt), master receiver (mr), slave transmitter (st) and slave receiver (sr). several of these m odes can be used in the same app lication. as an example, the twi can use mt mode to writ e data into a twi eeprom, mr mode to read the data back from the eeprom. if other masters are present in the system, some of these might transmit data to the twi, and then sr mode would be used. it is the application software that dec ides which modes are legal. the following sections describe each of these modes. possible status codes are described al ong with figures detailing data transmission in each of the modes. these figures contain the following abbreviations: s: start condition rs: repeated start condition r: read bit (high level at sda) w: write bit (low level at sda) a: acknowledge bit (low level at sda) a : not acknowledge bit (high level at sda) data: 8-bit data byte p: stop condition sla: slave address in figure 5-88 on page 207 to figure 5-94 on page 217 , circles are used to indicate that the twint flag is set. the numbers in the circles show the status code held in twsr, with the pre scaler bits masked to zero. at these points, actions must be taken by the application to continue or complete the twi transfer. the twi transfer is suspended until the twint flag is cleared by software. when the twint flag is set, the status code in twsr is us ed to determine the appropriate soft ware action. for each status code, the required software action and details of the following serial transfer are given in table 5-87 to table 5-90 . note that the prescaler bits are masked to zero in these tables. 6 wait3: in r16,twcr sbrs r16,twint rjmp wait3 while (!(twcr & (1< 205 ata6614q [datasheet] 9240h?auto?10/14 5.21.7.1 master transmitter mode in the master transmitter mode, a number of data bytes are transm itted to a slave receiver (see figure 5-87 ). in order to enter a master mode, a start condition must be transmitt ed. the format of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+w is transmitted, mt mode is entered, if sla+r is transmitted, mr mode is entered. all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 5-87. data transfer in master transmitter mode a start condition is sent by wr iting the following value to twcr: twen must be set to enable the 2-wire serial interface, twst a must be written to one to transmit a start condition and twint must be written to one to clear the twint flag. the twi will then test the 2-wire serial bus and generate a start condition as soon as the bus becomes free. after a start co ndition has been transmitted, the twint flag is set by hardware, and the status code in twsr will be 0x08 (see table 5-87 ). in order to enter mt mode, sla+w must be transmitted. this is done by writing sla+w to twdr. thereaft er the twint bit should be cleared (by writing it to one) to continue the transfer. this is accomplished by writing the following value to twcr: when sla+w have been transmitted and an ack nowledgement bit has been received, tw int is set again and a number of status codes in twsr are possible. possible status codes in master mode are 0x18, 0x20, or 0x38. the appropriate action to be taken for each of these status codes is detailed in table 5-87 . when sla+w has been successfully transmitte d, a data packet should be transmitted. th is is done by writing the data byte to twdr. twdr must only be written when twint is high. if not, the access will be discard ed, and the write collision bit (twwc) will be set in the twcr register. after updating twdr, th e twint bit should be cleared (by writing it to one) to continue the transfer. this is accomplished by writing the following value to twcr: this scheme is repeated until the last byte has been sent and the transfer is ended by gener ating a stop condition or a repeated start condition. a stop condition is ge nerated by writing the following value to twcr: a repeated start condition is generated by writing the following value to twcr: twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x device 1 master transmitter sda scl v cc device 3 device n ........ r1 r2 device 2 slave receiver
ata6614q [datasheet] 9240h?auto?10/14 206 after a repeated start condition (state 0x10) the 2-wire serial interface can access the same slave again, or a new slave without transmitting a stop condition. re peated start enables the master to swit ch between slaves, master transmitter mode and master receiver mode wit hout losing control of the bus. table 5-87. status codes for master transmitter mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x08 a start condition has been transmitted load sla+w 0 0 1 x sla+w will be transmitted; ack or not ack will be received 0x10 a repeated start condition has been transmitted load sla+w or load sla+r 0 0 0 0 1 1 x x sla+w will be transmitted; ack or not ack will be received sla+r will be transmitted; logic will switch to master receiver mode 0x18 sla+w has been transmitted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x20 sla+w has been transmitted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x28 data byte has been transmitted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x30 data byte has been transmitted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x38 arbitration lost in sla+w or data bytes no twdr action or no twdr action 0 1 0 0 1 1 x x 2-wire serial bus will be released and not addressed slave mode entered a start condition will be transmitted when the bus becomes free
207 ata6614q [datasheet] 9240h?auto?10/14 figure 5-88. formats and states in the master transmitter mode s successfull transmission to a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address not acknowledge received after a data byte arbitration lost and addressed as slave from master to slave any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero from slave to master arbitration lost in slave address or data byte sla w r s sla w aap ap r mr mt data a data $08 $18 $20 $38 $28 ap $30 $38 $10 a or a other master continues $68 $78 n a other master continues to corresponding states in slave mode a or a other master continues $b0
ata6614q [datasheet] 9240h?auto?10/14 208 5.21.7.2 master receiver mode in the master receiver mode, a number of data bytes are received from a slave transmitter (slave see figure 5-89 ). in order to enter a master mode, a start condit ion must be transmitted. the format of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+w is transmitted, mt mode is entered, if sla+r is transmitted, mr mode is entered. all the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. figure 5-89. data transfer in master receiver mode a start condition is sent by wr iting the following value to twcr: twen must be written to one to enable the 2-wire serial inte rface, twsta must be written to one to transmit a start condition and twint must be set to clear the twint flag. th e twi will then test the 2-wire serial bus and generate a start condition as soon as the bus become s free. after a start condition has been transmitted, the twint flag is set by hardware, and the status code in twsr will be 0x08 (see table 5-87 ). in order to enter mr mode, sla+r must be transmitted. this is done by writing sla+r to twdr. thereafter the twint bit should be cleared (by writing it to one) to continue the transfer. this is accomplished by writing the following value to twcr: when sla+r have been transmitted and an acknowledgement bit has been received, twint is set again and a number of status codes in twsr are possible. possible status codes in master mode are 0x38, 0x40, or 0x48. the appropriate action to be taken for each of these status codes is detailed in table 5-88 . received data can be read from the twdr register when the twint flag is set high by hardware. this scheme is repeated until the last byte has been received. after the last byte has been received, the mr should inform the st by sending a nack after the last received data byte. the transfer is ended by generating a stop condition or a repeated start c ondition. a stop condition is generated by writing the following value to twcr: a repeated start condition is generated by writing the following value to twcr: after a repeated start condition (state 0x10) the 2-wire serial interface can access the same slave again, or a new slave without transmitting a stop condition. re peated start enables the master to swit ch between slaves, master transmitter mode and master receiver mode wit hout losing control over the bus. twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x device 1 master receiver sda scl v cc device 3 device n ........ r1 r2 device 2 slave transmitter
209 ata6614q [datasheet] 9240h?auto?10/14 table 5-88. status codes for master receiver mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x08 a start condition has been transmitted load sla+r 0 0 1 x sla+r will be transmitted ack or not ack will be received 0x10 a repeated start condition has been transmitted load sla+r or load sla+w 0 0 0 0 1 1 x x sla+r will be transmitted ack or not ack will be received sla+w will be transmitted logic will switch to master transmitter mode 0x38 arbitration lost in sla+r or not ack bit no twdr action or no twdr action 0 1 0 0 1 1 x x 2-wire serial bus will be released and not addressed slave mode will be entered a start condition will be transmitted when the bus becomes free 0x40 sla+r has been transmitted; ack has been received no twdr action or no twdr action 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x48 sla+r has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x50 data byte has been received; ack has been returned read data byte or read data byte 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x58 data byte has been received; not ack has been returned read data byte or read data byte or read data byte 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset
ata6614q [datasheet] 9240h?auto?10/14 210 figure 5-90. formats and states in the master receiver mode 5.21.7.3 slave receiver mode in the slave receiver mode, a num ber of data bytes are received from a master transmitter (see figure 5-91 ). all the status codes mentioned in this section a ssume that the prescaler bits are zero or are masked to zero. figure 5-91. data transfer in slave receiver mode s successfull reception from a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address arbitration lost and addressed as slave arbitration lost in slave address or data byte from master to slave any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero from slave to master sla r r s sla r a data ap ap w mt mr data a data $08 $40 $48 $38 $50 $58 $38 $10 a a or a other master continues $68 $78 n a other master continues to corresponding states in slave mode a or a other master continues $b0 device 1 slave receiver sda v cc scl device 3 device n ........ r1 r2 device 2 master transmitter
211 ata6614q [datasheet] 9240h?auto?10/14 to initiate the slave receiver mode, twar and twcr must be initialized as follows: the upper 7 bits are the address to which the 2-wire serial interface will respond when addressed by a master. if the lsb is set, the twi will respond to the general call address (0x00), otherwise it will ignor e the general call address. twen must be written to one to enable the twi. the twea bit must be written to one to enable the acknowledgement of the device?s own slave address or the general call address. twsta and twsto must be written to zero. when twar and twcr have been initialized, the twi waits unti l it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?0? (write), the twi will operate in sr mo de, otherwise st mode is entered. after its own slave address and the write bit have b een received, the twint flag is set and a valid status code can be read from twsr . the status code is used to determine the appropriate software action. the appropriate action to be taken for each status code is detailed in table 5-89 . the slave receiver mode may also be entered if arbitration is lost while the twi is in th e master mode (see states 0x68 and 0x78). if the twea bit is reset during a transfer, the twi will return a ?not acknowledge? (?1?) to sda after the next received data byte. this can be used to indicate that the slave is not able to receive any more bytes. while twea is zero, the twi does not acknowledge its own slave address. however, the 2-wire serial bus is still monitored and a ddress recognition may resume at any time by setting twea. this implies that the twea bi t may be used to temporarily isolate the twi from the 2-wire serial bus. in all sleep modes other than idle mode, the clock system to the twi is turned off. if the twea bit is set, the interface can still acknowledge its own slave address or the general call addr ess by using the 2-wire serial bus clock as a clock source. the part will then wake up from sleep and the twi will hold t he scl clock low during the wake up and until the twint flag is cleared (by writing it to one). further data reception will be carried out as normal, with the avr ? clocks running as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long time, blocking other data transmissions. note that the 2-wire serial interface data register ? twdr does not reflect the last byte present on the bus when waking up from these sleep modes. twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x
ata6614q [datasheet] 9240h?auto?10/14 212 table 5-89. status codes for slave receiver mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x60 own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x68 arbitration lost in sla+r/w as master; own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x70 general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x78 arbitration lost in sla+r/w as master; general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x80 previously addressed with own sla+w; data has been received; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x88 previously addressed with own sla+w; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free
213 ata6614q [datasheet] 9240h?auto?10/14 0x90 previously addressed with general call; data has been received; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x98 previously addressed with general call; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0xa0 a stop condition or repeated start condition has been received while still addressed as slave no action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free table 5-89. status codes for slave receiver mode (continued) status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea
ata6614q [datasheet] 9240h?auto?10/14 214 figure 5-92. formats and states in the slave receiver mode s reception of the own slave address and one or more data bytes. all are acknowledged last data byte received is not acknowledged last data byte received is not acknowledged arbitration lost as master and addressed as slave arbitration lost as master and as slave by general call from master to slave any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero from slave to master sla w a data ap or s a data a data $60 $68 $80 $80 $a0 $88 a p or s a n $90 $90 $a0 $98 p or s a reception of the general call address and one or more data bytes a $70 general call data ap or s a data $78 a
215 ata6614q [datasheet] 9240h?auto?10/14 5.21.7.4 slave transmitter mode in the slave transmitter mode, a number of data bytes are transmitted to a master receiver (see figure 5-93 ). all the status codes mentioned in this section a ssume that the prescaler bits are zero or are masked to zero. figure 5-93. data transfer in slave transmitter mode to initiate the slave transmitter mode, tw ar and twcr must be initialized as follows: the upper seven bits are the address to which the 2-wire seri al interface will respond when addressed by a master. if the lsb is set, the twi will respond to the general call address (0 x00), otherwise it will ignore the general call address. twen must be written to one to enable the twi. the twea bit must be written to one to enable the acknowledgement of the device?s own slave address or the general call address. twsta and twsto must be written to zero. when twar and twcr have been initialized, the twi waits unti l it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?1? (read), the twi will operate in st mod e, otherwise sr mode is entered. after its own slave address and the write bit have been received, the twint flag is set and a valid status code can be read from twsr . the status code is used to determine the appropriate software action. the appropriate action to be taken for each status code is detailed in table 5-90 . the slave transmitter mode may also be entered if arbitration is lost while the twi is in the master mode (see state 0xb0). if the twea bit is written to zero during a transfer, the twi will transmit the last byte of the transfer. state 0xc0 or state 0xc8 will be entered, depending on whether the ma ster receiver transmits a nack or ack after the final byte. the twi is switched to the not addressed slave mode, and will ignore the master if it continues the transfer. thus the master receiver receives all ?1? as serial data. state 0xc8 is entered if the master demands additi onal data bytes (by transmitting ack), even though the slave has transmitted the last byte (twea zero and expecting nack from the master). while twea is zero, the twi does not respond to its own slave address. however, the 2-wire se rial bus is still monitored and address recognition may resume at any time by sett ing twea. this implies that the twea bit may be used to temporarily isolate the twi from the 2-wire serial bus. in all sleep modes other than idle mode, the clock system to the twi is turned off. if the twea bit is set, the interface can still acknowledge its own slave address or the general call addr ess by using the 2-wire serial bus clock as a clock source. the part will then wake up from sleep and the twi will hold the scl clock will low during the wake up and until the twint flag is cleared (by writing it to one). further data trans mission will be carried out as normal, with the avr ? clocks running as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long time, blocking other data transmissions. note that the 2-wire serial interface data register ? twdr does not reflect the last byte present on the bus when waking up from these sleep modes. twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x device 1 slave transmitter sda v cc scl device 3 device n ........ r1 r2 device 2 master receiver
ata6614q [datasheet] 9240h?auto?10/14 216 table 5-90. status codes for slave transmitter mode status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0xa8 own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be received 0xb0 arbitration lost in sla+r/w as master; own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be received 0xb8 data byte in twdr has been transmitted; ack has been received load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be received 0xc0 data byte in twdr has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0xc8 last data byte in twdr has been transmitted (twea = ?0?); ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free
217 ata6614q [datasheet] 9240h?auto?10/14 figure 5-94. formats and states in the slave transmitter mode 5.21.7.5 miscellaneous states there are two status code s that do not correspond to a defined twi state, see table 5-91 . status 0xf8 indicates that no relevant information is availabl e because the twint flag is not set. this occurs between other states, and when the twi is not involved in a serial transfer. status 0x00 indicates that a bus error has occurred during a 2- wire serial bus transfer. a bus error occurs when a start or stop condition occurs at an illegal position in the format fram e. examples of such illegal positions are during the serial transfer of an address byte, a data byte, or an acknowledge bit. when a bus error occurs, twin t is set. to recover from a bus error, the twsto flag must set and twint must be cleared by writing a logic one to it. this causes the twi to enter the not addressed slave mode and to clear the twsto flag (no ot her bits in twcr are affected). the sda and scl lines are released, and no stop condition is transmitted. s reception of the own slave address and one or more data bytes last data byte transmitted. switched to not adressed slave (twea = 0 arbitration lost as master and addressed as slave from master to slave any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero from slave to master sla r a data ap or s a data all 1s a data $a8 $b0 $b8 $c0 $c8 a p or s a n table 5-91. miscellaneous states status code (twsr) prescaler bits are 0 status of the 2-wire serial bus and 2-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0xf8 no relevant state information available; twint = ?0? no twdr action no twcr action wait or proceed current transfer 0x00 bus error due to an illegal start or stop condition no twdr action 0 1 1 x only the internal hardware is affected, no stop condition is sent on the bus. in all cases, the bus is released and twsto is cleared.
ata6614q [datasheet] 9240h?auto?10/14 218 5.21.7.6 combining several twi modes in some cases, several twi modes must be combined in order to complete the desired action. consider for example reading data from a serial eeprom. ty pically, such a transfer involves the following steps: 1. the transfer must be initiated. 2. the eeprom must be instructed what location should be read. 3. the reading must be performed. 4. the transfer must be finished. note that data is transmitted both from master to slave and vice versa. the master must instru ct the slave what location it wants to read, requiring the use of the mt mode. subsequently, data must be read from the sl ave, implying the use of the mr mode. thus, the transfer direction must be changed. the mast er must keep control of the bus during al l these steps, and the steps should be carri ed out as an atomical operat ion. if this principle is violated in a multi ma ster system, another maste r can alter the data pointer in the eeprom between steps 2 and 3, and the master will read the wrong data location. such a change in transfer direction is accomplished by transmitti ng a repeated start between the transmission of the address byte and reception of the da ta. after a repeated start, the master keeps ownership of the bus. the following figure shows the flow in this transfer. figure 5-95. combi ning several twi modes to access a serial eeprom 5.21.8 multi-master systems and arbitration if multiple masters are connec ted to the same bus, transmissions may be init iated simultaneously by one or more of them. the twi standard ensures that such situat ions are handled in such a way that one of the masters will be allowed to proceed with the transfer, and that no data will be lost in the process. an example of an arbi tration situation is depicted below, wher e two masters are trying to trans mit data to a slave receiver. figure 5-96. an arbitration example several different scenarios may arise dur ing arbitration, as described below: two or more masters are performing i dentical communication with the same slave. in this case, neither the slave nor any of the masters will know about the bus contention. two or more masters are accessing the same slave with differ ent data or direction bit. in this case, arbitration will occur, either in the read/write bit or in the data bits. the masters trying to output a one on sda while another master outputs a zero will lose the arbitration. losing master s will switch to not addressed slave mode or wait until the bus is free and transmit a new start condition, depending on application software action. s s = start p = stop r s = repeated start p r s a sla + w a a a address master transmitter transmitted from master to slave transmitted from slave to master master receiver data sla + r device 1 master transmitter sda scl v cc device n ........ r1 r2 device 2 master transmitter device 3 slave receiver
219 ata6614q [datasheet] 9240h?auto?10/14 two or more masters are accessing different slaves. in this case, arbitration will occur in the sla bits. masters trying to output a one on sda while another master outputs a zero will lose the arbitration. masters losing arbitration in sla will switch to slave mode to check if they are being addre ssed by the winning master. if addressed, they will switch to sr or st mode, depending on the value of the read/write bit. if they are not being addressed, they will switch to not addressed slave mode or wait until the bus is free and transmit a new star t condition, depending on application software action. this is summarized in figure 5-97 . possible status values are given in circles. figure 5-97. possible status codes caused by arbitration 5.21.9 register description 5.21.9.1 twbr ? twi bit rate register ? bits 7..0 ? twi bit rate register twbr selects the division factor for the bit rate generator. th e bit rate generator is a frequ ency divider which generates the scl clock frequency in the master modes. see section 5.21.5.2 ?bit rate generator unit? on page 200 for calculating bit rates. 5.21.9.2 twcr ? twi control register the twcr is used to control the operation of the twi. it is used to enable the twi, to initiate a master access by applying a start condition to the bus, to generate a receiver acknowledge , to generate a stop condition, and to control halting of the bus while the data to be written to the bus are written to the twdr. it also indica tes a write collision if data is attempted written to twdr while the register is inaccessible. own address/ general call received direction twi bus will be released and not addressed slave mode will be entered a start condition will be transmitted when the bus becomes free data byte will be received and not ack will be returned data byte will be received and ack will be returned last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be received start sla no yes write read 38 68/78 arbitration lost in sla arbitration lost in data data stop b0 bit 76543210 (0xb8) twbr7 twbr6 twbr5 twbr4 twbr3 twbr2 twbr1 twbr0 twbr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xbc) twint twea twsta twsto twwc twen ? twie twcr read/write r/w r/w r/w r/w r r/w r r/w initial value 0 0 0 0 0 0 0 0
ata6614q [datasheet] 9240h?auto?10/14 220 ? bit 7 ? twint: twi interrupt flag this bit is set by hardware when the twi has finished its curr ent job and expects application software response. if the i-bit i n sreg and twie in twcr are set, the mcu will jump to the twi interrupt vector. while the twin t flag is set, the scl low period is stretched. the twint flag must be cleared by software by writing a logic one to it. note that this flag is not automatically cleared by hardware when execut ing the interrupt routine. also note that clearing this flag starts the operation of the twi, so all accesses to the twi address register (twar) , twi status register (twsr), and twi data register (twdr) must be complete before clearing this flag. ? bit 6 ? twea: twi enable acknowledge bit the twea bit controls the generation of the acknowledge pulse. if the twea bit is written to one, the ack pulse is generated on the twi bus if the following conditions are met: 1. the device?s own slave address has been received. 2. a general call has been received, while the twgce bit in the twar is set. 3. a data byte has been received in master receiver or slave receiver mode. by writing the twea bit to zero, the device can be virtually disconnected from the 2-wire serial bus temporarily. address recognition can then be resumed by writing the twea bit to one again. ? bit 5 ? twsta: twi start condition bit the application writes the twsta bit to one when it desires to become a master on the 2-wire serial bus. the twi hardware checks if the bus is avail able, and gener ates a start condition on the bus if it is free. however, if the bus is not free, the twi waits until a stop condition is detect ed, and then generates a new start cond ition to claim the bus master status. twsta must be cleared by software when the start condition has been transmitted. ? bit 4 ? twsto: twi stop condition bit writing the twsto bit to one in master mode will generate a stop condition on the 2-wire serial bus. when the stop condition is executed on the bus, the twsto bit is cleared automatically. in slav e mode, setting the twsto bit can be used to recover from an error condition. this will not generate a stop condition, but the twi returns to a well-defined unaddressed slave mode and releases the sc l and sda lines to a high impedance state. ? bit 3 ? twwc: twi write collision flag the twwc bit is set when attemp ting to write to the twi data register ? twdr when twint is low. this flag is cleared by writing the twdr register when twint is high. ? bit 2 ? twen: twi enable bit the twen bit enables twi operation and activates the twi interf ace. when twen is written to one, the twi takes control over the i/o pins connected to the scl and sda pins, enabling the slew-rate limiters and spike filt ers. if this bit is written to zero, the twi is swit ched off and all twi transmissions are termina ted, regardless of any ongoing operation. ? bit 1 ? res: reserved bit this bit is a reserved bit and will always read as zero. ? bit 0 ? twie: twi interrupt enable when this bit is written to one, and the i- bit in sreg is set, the twi interrupt r equest will be activated for as long as the twint flag is high.
221 ata6614q [datasheet] 9240h?auto?10/14 5.21.9.3 twsr ? twi status register ? bits 7..3 ? tws: twi status these 5 bits reflect the status of the twi logic and the 2-wire serial bus. the di fferent status codes are described later in t his section. note that the value read from twsr contains both the 5-bit status value and the 2-bit prescaler value. the application designer should mask the prescaler bits to zero when checking the status bits. this makes status checking independent of prescaler setting. this approach is used in this datasheet, unless otherwise noted. ? bit 2 ? res: reserved bit this bit is reserved and will always read as zero. ? bits 1..0 ? twps: twi prescaler bits these bits can be read and written, and control the bit rate prescaler. to calculate bit rates, see section 5.21.5.2 ?bit rate generator unit? on page 200 . the value of twps1..0 is used in the equation. 5.21.9.4 twdr ? twi data register in transmit mode, twdr contains the nex t byte to be transmitted. in receive mo de, the twdr contains the last byte received. it is writable while the twi is not in the process of shifting a byte . this occurs when the twi interrupt flag (twint ) is set by hardware. note that the data register cannot be init ialized by the user before the fi rst interrupt occurs. the data i n twdr remains stable as long as twint is set. while data is shifted out, data on the bus is simultaneously shifted in. twdr always contains the last byte present on the bus, except a fter a wake up from a sleep mode by the twi interrupt. in this case, the contents of twdr is undefined. in the case of a lost bus arbitr ation, no data is lost in the transition from ma ster to slave. handling of the ack bit is contr olled automatically by the twi logic, the cpu cannot access the ack bit directly. ? bits 7..0 ? twd: twi data register these eight bits constitute the next data byte to be transmitte d, or the latest data byte received on the 2-wire serial bus. bit 76543210 (0xb9) tws7 tws6 tws5 tws4 tws3 ? twps1 twps0 twsr read/write r r r r r r r/w r/w initial value11111000 table 5-92. twi bit rate prescaler twps1 twps0 prescaler value 0 0 1 0 1 4 1 0 16 1 1 64 bit 76543210 (0xbb) twd7 twd6 twd5 twd4 twd3 twd2 twd1 twd0 twdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 1 1 1 1 1 1 1 1
ata6614q [datasheet] 9240h?auto?10/14 222 5.21.9.5 twar ? twi (slave) address register the twar should be loaded with the 7-bit slave address (in the seven most significant bits of twar) to which the twi will respond when programmed as a slave transmitter or receiver , and not needed in the master modes. in multi master systems, twar must be set in masters which c an be addressed as slaves by other masters. the lsb of twar is used to enable recognition of the general call address (0x00). there is an associated address comparator that looks for the slave address (or general call address if enabled) in the received serial address. if a match is found, an interrupt request is generated. ? bits 7..1 ? twa: twi (slave) address register these seven bits constitute the slave address of the twi unit. ? bit 0 ? twgce: twi general call recognition enable bit if set, this bit enables the recognition of a general call given over the 2-wire serial bus. 5.21.9.6 twamr ? twi (slave) address mask register ? bits 7..1 ? twam: twi address mask the twamr can be loaded with a 7-bit slave address mask. each of the bits in twamr can mask (disable) the corresponding address bits in the twi address register (twar) . if the mask bit is set to one then the address match logic ignores the compare between the incoming address bit and the corresponding bit in twar. figure 5-98 shown the address match logic in detail. figure 5-98. twi address match logic, block diagram ? bit 0 ? res: reserved bit this bit is an unused bit in the atmega328p, and will always read as zero. bit 76543210 (0xba) twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce twar read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 1 1 1 1 1 1 1 0 bit 76543210 (0xbd) twam[6:0] ? twamr read/write r/w r/w r/w r/w r/w r/w r/w r initial value 0 0 0 0 0 0 0 0 twar0 address match twamr0 address bit comparator 6 to 1 address bit comparator 0 address bit 0
223 ata6614q [datasheet] 9240h?auto?10/14 5.22 analog comparator 5.22.1 overview the analog comparator compares the input values on the positive pin ain0 and negative pin ain1. when the voltage on the positive pin ain0 is higher than the vo ltage on the negative pin ain1, the analog comparator output, aco, is set. the comparator?s output can be set to trigger the timer/counter1 input capture function. in addition, the comparator can trigger a separate interrupt, exclusive to the analog comparator. the user can select interrupt triggering on comparator output rise, fall or toggle. a block diagram of the comparator and its surrounding logic is shown in figure 5-99 . the power reduction adc bit, pradc, in section 5.9.10 ?minimizing po wer consumption? on page 60 must be disabled by writing a logical zero to be able to use the adc input mux. figure 5-99. analog comparator block diagram (2) notes: 1. see table 5-93 on page 223 . 2. refer to table 5-37 on page 94 for analog comparator pin placement. 5.22.2 analog comparator multiplexed input it is possible to select any of the adc7..0 pins to replace the negative input to the analog comparator. the adc multiplexer is used to select this input, and consequently, the adc must be switched off to utilize this f eature. if the analog comparator multiplexer enable bit (acme in adcsrb) is set and the adc is switched off (aden in adcsra is zero), mux2..0 in admux select the input pin to replace the negativ e input to the analog comparator, as shown in table 5-93 . if acme is cleared or aden is set, ain1 is applied to the negative input to the analog comparator. bandgap reference interrupt select ain0 vcc acis1 adc multiplexer output (1) acis0 acic aco acie analog comparator irq aci to t/c1 capture trigger mux acbg acme aden acd + - ain1 table 5-93. analog comparator multiplexed input acme aden mux2..0 analog comparator negative input 0 x xxx ain1 1 1 xxx ain1 1 0 000 adc0 1 0 001 adc1 1 0 010 adc2 1 0 011 adc3 1 0 100 adc4 1 0 101 adc5 1 0 110 adc6 1 0 111 adc7
ata6614q [datasheet] 9240h?auto?10/14 224 5.22.3 register description 5.22.3.1 adcsrb ? adc contro l and status register b ? bit 6 ? acme: analog comparator multiplexer enable when this bit is written logic one and the adc is switched of f (aden in adcsra is zero), the adc multiplexer selects the negative input to the analog comparator. when this bit is written logic zero, ain1 is applied to the negative input of the analog comparator. for a detailed description of this bit, see section 5.22.2 ?analog comparator multiplexed input? on page 223 . 5.22.3.2 acsr ? analog comparator control and status register ? bit 7 ? acd: analog comparator disable when this bit is written logic one, the power to the analog compar ator is switched off. this bit can be set at any time to turn off the analog comparator. this will reduce power consumption in active and idle mode. when changing the acd bit, the analog comparator interrupt must be disabled by clearing the acie bit in acsr. otherwise an interrupt can occur when the bit is changed. ? bit 6 ? acbg: analog comparator bandgap select when this bit is set, a fixed bandgap reference voltage replaces the positive input to the analog comparator. when this bit is cleared, ain0 is applied to the positive in put of the analog comparat or. when the bandgap reference is used as input to the analog comparator, it will take a certain time for the voltage to stabilize. if not stabilized, th e first conversion may give a wrong value. see section 5.10.7 ?internal voltage reference? on page 67 . ? bit 5 ? aco: analog comparator output the output of the analog compar ator is synchronized and then di rectly connected to aco. the synchronization introduces a delay of 1 - 2 clock cycles. ? bit 4 ? aci: analog comparator interrupt flag this bit is set by hardware when a comparator output event triggers the interrupt mode defined by acis1 and acis0. the analog comparator interrupt routine is execut ed if the acie bit is set and the i-bit in sreg is set. aci is cleared by hardware when executing the corresponding interrupt handling vector. alter natively, aci is cleared by writing a logic one to the flag. ? bit 3 ? acie: analog comparator interrupt enable when the acie bit is written logic one and the i-bit in the stat us register is set, the analog comparator interrupt is activate d. when written logic zero, the interrupt is disabled. ? bit 2 ? acic: analog comparator input capture enable when written logic one, this bit enables the input capture function in timer/counter1 to be triggered by the analog comparator. the comparator out put is in this case directly connected to the input capture front- end logic, making the comparator utilize the noise c anceler and edge select features of the timer/ counter1 input capture interrupt. when written logic zero, no connection between the analog comparator and t he input capture function exists. to make the comparator trigger the timer/counter1 input capture in terrupt, the icie1 bit in th e timer interrupt mask register (timsk1) must be set. bit 7 6543210 (0x7b) ?acme ? ? ? adts2 adts1 adts0 adcsrb read/write r r/w r r r r/w r/w r/w initial value0 0000000 bit 76543210 0x30 (0x50) acd acbg aco aci acie acic acis1 acis0 acsr read/write r/w r/w r r/w r/w r/w r/w r/w initial value00n/a00000
225 ata6614q [datasheet] 9240h?auto?10/14 ? bits 1, 0 ? acis1, acis0: analog comparator interrupt mode select these bits determine which comparator events that trigger th e analog comparator interrupt. the different settings are shown in table 5-94 . when changing the acis1/acis0 bits, the analog comparator interrupt must be disabled by clearing its interrupt enable bit in the acsr register. otherwise an interr upt can occur when the bits are changed. 5.22.3.3 didr1 ? digital input disable register 1 ? bit 7..2 ? res: reserved bits these bits are unused bits in the atmega328p, and will always read as zero. ? bit 1, 0 ? ain1d, ain0d: ai n1, ain0 digital input disable when this bit is written logic one, the digital input buffer on the ain1/0 pin is disabled. the corresponding pin register bit will always read as zero when this bit is set. when an analog signal is applied to the ain1/0 pin and the digital input from this pi n is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. table 5-94. acis1/acis0 settings acis1 acis0 interrupt mode 0 0 comparator interrupt on output toggle. 0 1 reserved 1 0 comparator interrupt on falling output edge. 1 1 comparator interrupt on rising output edge. bit 76543210 (0x7f) ? ? ? ? ? ? ain1d ain0d didr1 read/write r r r r r r r/w r/w initial value 0 0 0 0 0 0 0 0
ata6614q [datasheet] 9240h?auto?10/14 226 5.23 analog-to-digital converter 5.23.1 features 10-bit resolution 0.5 lsb integral non-linearity 2 lsb absolute accuracy 65s to 260s conversion time up to 15ksps 6 multiplexed single ended input channels 2 additional multiplexed single ended input channels temperature sensor input channel optional left adjustment for adc result readout 0 to v cc adc input voltage range selectable 1.1v adc reference voltage free running or single conversion mode interrupt on adc conversion complete sleep mode noise canceler 5.23.2 overview the atmega328p features a 10-bit succe ssive approximation adc. the adc is connected to an 8-channel analog multiplexer which allows eight single-ended voltage inputs cons tructed from the pins of po rt a. the single-ended voltage inputs refer to 0v (gnd). the adc contains a sample and hold circuit which ensures that the input voltage to the adc is held at a constant level during conversion. a block diagram of the adc is shown in figure 5-100 on page 227 . the adc has a separate analog supply voltage pin, av cc . av cc must not differ more than 0.3v from v cc . see the paragraph section 5.23.6 ?adc noise canceler? on page 232 on how to connect this pin. internal reference voltages of nominally 1.1v or av cc are provided on-chip. the voltage reference may be externally decoupled at the aref pin by a ca pacitor for better noise performance. the power reduction adc bit, pradc, in section 5.9.10 ?minimizing po wer consumption? on page 60 must be disabled by writing a logical zero to enable the adc. the adc converts an analog input voltage to a 10-bit digital value through successive approximation. the minimum value represents gnd and the maximum value represents the voltage on the aref pin minus 1 lsb. optionally, av cc or an internal 1.1v reference voltage may be connected to the aref pin by writing to the refsn bits in the admux register. the internal voltage reference may thus be decoupled by an external capacitor at the aref pin to improve noise immunity.
227 ata6614q [datasheet] 9240h?auto?10/14 figure 5-100. analog to digital co nverter block schematic operation the analog input channel is selected by writing to the mux bits in admux. any of the adc input pins, as well as gnd and a fixed bandgap voltage reference, can be selected as single ended inputs to the adc. the adc is enabled by setting the adc enable bit, aden in adcsra. voltage reference and input ch annel selections will not go into effect until aden is set. the adc does not consume power when aden is cleared, so it is recommended to switch off the adc before entering power saving sleep modes. the adc generates a 10-bit result which is presented in the adc data registers, adch and adcl. by default, the result is presented right adjusted, but can optionally be presen ted left adjusted by setting the adlar bit in admux. if the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read adch. otherwise, adcl mus t be read first, then adch, to ensure that the content of the data registers belongs to the same conversion. once adcl is read, adc access to data registers is blocked. prescaler - + 15 0 adc multiplexer select (admux) mux decoder avcc 8-bit data bus aref gnd adc7 adc6 adc5 adc4 adc3 adc2 adc1 adc0 10-bit dac input mux sample and hold comparator internal 1.1v reference conversion logic adc conversion complete irq adc ctrl and status register (adcsra) adc data register (adch/adcl) adif aden refs1 refs0 adlar mux3 mux2 mux1 mux0 channel selection adsc adif adfr adps2 adps1 adps0 adie bandgap reference temperature sensor adc[9:0] adc multiplexer output
ata6614q [datasheet] 9240h?auto?10/14 228 this means that if adcl has been read, and a conversion comp letes before adch is read, neither register is updated and the result from the conversion is lost. when adch is read, adc access to the adch and adcl registers is re-enabled. the adc has its own interrupt which can be triggered when a conversion completes. when adc access to the data registers is prohibited between reading of ad ch and adcl, the interrupt will trigger even if the result is lost. 5.23.3 starting a conversion a single conversion is started by disabli ng the power reduction adc bit, pradc, in section 5.9.10 ?minimizing power consumption? on page 60 by writing a logical zero to it and writing a logical one to the adc start conversion bit, adsc. this bit stays high as long as the conversion is in progress and will be cleared by hardware when the conversion is completed. if a different data channel is selected while a conversion is in progress, the adc will finish the current conversion before performing the channel change. alternatively, a conversion can be triggered automatically by various sources. auto triggering is enabled by setting the adc auto trigger enable bit, adate in adcsra. the trigger source is selected by setting the adc trigger select bits, adts in adcsrb (see description of the adts bits for a list of the trigger sources). when a positive edge occurs on the selected trigger signal, the adc prescaler is reset and a conversion is star ted. this provides a method of starting conversions at fixed intervals. if the trigger signal still is set when the conversion comp letes, a new conversion will not be started. if another positive edge occurs on the trigger signal during conversion, the edge will be ignored. note that an interrupt flag will be set even if the specific interrupt is disabled or the global interrupt enable bit in sreg is cleared. a conversion can thus be triggered without causing an interrupt. howe ver, the interrupt flag must be cleared in order to trigger a new conversion at the next interrupt event. figure 5-101. adc auto trigger logic using the adc interrupt flag as a trigger source makes the a dc start a new conversion as soon as the ongoing conversion has finished. the adc then operates in free running mode, constant ly sampling and updating the adc data register. the first conversion must be started by writing a logical one to the adsc bit in adcsra. in this mode the adc will perform successive conversions independently of whether t he adc interrupt flag, adif is cleared or not. if auto triggering is enabled, single conv ersions can be started by writing adsc in adcsra to one. adsc can also be used to determine if a conversion is in progress. the adsc bit wi ll be read as one during a conv ersion, independently of how the conversion was started. edge detector conversion logic prescaler adif adsc adate start clk adc adts[2:0] . . . . source 1 source n
229 ata6614q [datasheet] 9240h?auto?10/14 5.23.4 prescaling and conversion timing figure 5-102. adc prescaler by default, the successive approximation circuitry requires an input clock frequency between 50khz and 200khz to get maximum resolution. if a lower resolution than 10 bits is needed, the input clock frequency to the adc can be higher than 200khz to get a higher sample rate. the adc module contains a prescaler, which generates an acceptable adc clock frequency from any cpu frequency above 100khz. the prescaling is set by the adps bits in adcsra. the prescaler starts counting from the moment the adc is switched on by setting the aden bit in adcsra. the prescaler keeps running for as long as the aden bit is set, and is continuously reset when aden is low. when initiating a single ended conversion by setting the adsc bi t in adcsra, the conversion starts at the following rising edge of the adc clock cycle. a normal conversion takes 13 adc clock cycles . the first conversion after the adc is switched on (aden in adcsra is set) takes 25 adc clock cycles in order to initialize the analog circuitry. when the bandgap reference voltage is used as input to the adc, it will ta ke a certain time for the voltage to stabilize. if no t stabilized, the first value read after the first conversion may be wrong. the actual sample-and-hold takes place 1.5 adc clock cycles after the start of a normal conversion and 13.5 adc clock cycles after the start of an first conversion. when a conversion is complete, the result is writt en to the adc data registers, and adif is set. in single conversion mode, adsc is clea red simultaneously. the software may then set adsc again, and a new conversion will be initiated on the first rising adc clock edge. when auto triggering is used, the prescaler is reset when the trigger event occurs. this assures a fixed delay from the trigger event to the start of conversi on. in this mode, the sample-a nd-hold takes place two adc clo ck cycles after the rising edge on the trigger source signal. thre e additional cpu clock cycles ar e used for synchronization logic. in free running mode, a new conversion w ill be started immediately after the conversion completes, while adsc remains high. for a summary of conversion times, see table 5-95 on page 231 . 7-bit adc prescaler adc clock source aden start ck adps0 adps1 adps2 reset ck/2 ck/4 ck/8 ck/16 ck/32 ck/64 ck/128
ata6614q [datasheet] 9240h?auto?10/14 230 figure 5-103. adc timing di agram, first conversion (single conversion mode) figure 5-104. adc ti ming diagram, si ngle conversion 1 2 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 2 3 cycle number first conversion sign and msb of result lsb of result next conversion mux and refs update conversion complete mux and refs update adc clock aden adsc adif adch adcl sample and hold 12345678910111213 123 cycle number one conversion sign and msb of result lsb of result next conversion mux and refs update conversion complete mux and refs update adc clock adsc adif adch adcl sample and hold
231 ata6614q [datasheet] 9240h?auto?10/14 figure 5-105. adc timing diagram, auto triggered conversion figure 5-106. adc timi ng diagram, free ru nning conversion table 5-95. adc co nversion time condition sample and hold (cycles from start of conversion) conversion time (cycles) first conversion 13.5 25 normal conversions, single ended 1.5 13 auto triggered conversions 2 13.5 12345678910111213 12 cycle number one conversion sign and msb of result lsb of result next conversion mux and refs update prescaler reset prescaler reset conversion complete adc clock trigger source adif adate adch adcl sample and hold 11 12 13 1 2 3 4 cycle number one conversion sign and msb of result lsb of result next conversion mux and refs update conversion complete adc clock adsc adif adch adcl sample and hold
ata6614q [datasheet] 9240h?auto?10/14 232 5.23.5 changing channel or reference selection the muxn and refs1:0 bits in the admux register are singl e buffered through a temporary register to which the cpu has random access. this ensures that the channels and referenc e selection only takes place at a safe point during the conversion. the channel and reference select ion is continuously updated until a conv ersion is started. once the conversion starts, the channel and reference selection is locked to ensure a sufficient sampling time for the adc. continuous updating resumes in the last adc clock cycle before the conversion completes (adif in adcsra is set). note that the conversion starts on the following rising adc clock edge after adsc is wri tten. the user is thus advised not to write new channel or reference selection values to admux until one adc clock cycle after adsc is written. if auto triggering is used, the exact time of the triggering event can be indetermin istic. special care must be taken when updating the admux register, in order to control wh ich conversion will be affected by the new settings. if both adate and aden is written to one, an interrupt event ca n occur at any time. if the admux register is changed in this period, the user cannot tell if the next conversion is based on the old or the new settings. admux can be safely updated in the following ways: a. when adate or aden is cleared. b. during conversion, minimum one a dc clock cycle after the trigger event. c. after a conversion, before the interrupt flag used as trigger source is cleared. when updating admux in one of these conditions, the new settings will affect the next adc conversion. 5.23.5.1 adc input channels when changing channel selections, the user should observe the following guidelines to ensure that the correct channel is selected: in single conversion mode, always select the channel before starting the conversion. the channel selection may be changed one adc clock cycle after writing one to adsc. however, the simp lest method is to wait fo r the conversion to complete before changing the channel selection. in free running mode, always select the ch annel before starting the first conversion. the channel selection may be changed one adc clock cycle after writing one to adsc. however, the simp lest method is to wait for the first conversion to complete, and then change the channel selection. si nce the next conversion has already star ted automatically, the next result will reflect the previous channel selection. subsequent conversions will reflect the new channel selection. 5.23.5.2 adc voltage reference the reference voltage for the adc (v ref ) indicates the conversion range for the adc. single ended channels that exceed v ref will result in code s close to 0x3ff. v ref can be selected as either av cc , internal 1.1v reference, or external aref pin. av cc is connected to the adc through a passive switch. the inte rnal 1.1v reference is generated from the internal bandgap reference (v bg ) through an internal amplifier. in either case, the exte rnal aref pin is directly c onnected to the adc, and the reference voltage can be made more immune to noise by connecting a capacitor between the aref pin and ground. v ref can also be measured at the aref pin with a high impedance voltmeter. note that v ref is a high impedance source, and only a capacitive load should be connected in a system. if the user has a fixed voltage source connected to the aref pin, the user may not use the other reference voltage options in the application, as they will be shorte d to the external voltage. if no external voltage is applied to the aref pin, the use r may switch between av cc and 1.1v as reference selection. the first adc conversion result after switching reference voltage source may be inaccurate, and the user is advised to discard this result. 5.23.6 adc noise canceler the adc features a noise canceler that enables conversion during sleep mode to reduce noise induced from the cpu core and other i/o peripherals. the noise canceler can be used with adc noise reduction and idle mode. to make use of this feature, the following procedure should be used: a. make sure that the adc is enabled and is not busy co nverting. single conversion mode must be selected and the adc conversion complete interrupt must be enabled. b. enter adc noise reduction mode (or idle mode). the ad c will start a conversion once the cpu has been halted.
233 ata6614q [datasheet] 9240h?auto?10/14 c. if no other interrupts occur before t he adc conversion completes, the adc interrupt will wake up the cpu and execute the adc conversion complete interrupt routine. if another interrupt wakes up the cpu before the adc conversion is complete, that interrup t will be executed, and an adc conversion complete interrupt request will be generated when the adc conversion completes. the cpu wi ll remain in active mode until a new sleep command is executed. note that the adc will not be automatically turned off when entering ot her sleep modes than idle mode and adc noise reduction mode. the user is advised to write zero to aden before entering such sleep modes to avoid excessive power consumption. 5.23.6.1 analog input circuitry the analog input circuitry for single ended channels is illustrated in figure 5-107 on page 233 an analog source applied to adcn is subjected to the pin capacitance and input leakage of t hat pin, regardless of whether that channel is selected as input for the adc. when the channel is selected, the source must drive the s/h capacitor through the series resistance (combined resistance in the input path). the adc is optimized for analog signals wi th an output impedance of approximately 10k or less. if such a source is used, the sampling time will be negligible. if a source with higher impedance is used, the sampling time will depend on how long time the source needs to charge the s/h capacitor, with can vary widely. the user is recommended to only use low impedance sources with slowly varying signals, since this minimizes the required charge transfer to the s/h capacitor. signal components higher than the nyquist frequency (f adc /2) should not be present for eit her kind of channels, to avoid distortion from unpredictable signal convol ution. the user is advised to remove high frequency components with a low-pass filter before applying the signals as inputs to the adc. figure 5-107. analog input circuitry 5.23.6.2 analog noise canceling techniques digital circuitry inside and outside the device generates emi which might affect the accuracy of analog measurements. if conversion accuracy is critical, the noise level can be reduced by applying the following techniques: a. keep analog signal paths as short as possible. make sure analog tracks run over the analog ground plane, and keep them well away from hi gh-speed switching digital tracks. b. the av cc pin on the device should be connected to the digital v cc supply voltage via an lc network as shown in figure 5-108 . c. use the adc noise canceler function to reduce induced noise from the cpu. d. if any adc [3..0] port pins are used as digital outputs, it is essential that these do not switch while a conversion is in progress. however, using the 2-wire interface (adc4 and adc5) will only affect the conversion on adc4 and adc5 and not the other adc channels. i il v cc /2 c s/h = 14pf i ih adcn 1 to 100k
ata6614q [datasheet] 9240h?auto?10/14 234 figure 5-108. adc power connections 5.23.6.3 adc accuracy definitions an n-bit single-ended adc converts a voltage linearly between gnd and v ref in 2 n steps (lsbs). the lowest code is read as 0, and the highest code is read as 2 n -1. several parameters describe the deviation from the ideal behavior: offset: the deviation of the fi rst transition (0x000 to 0x001) compared to t he ideal transition (at 0.5 lsb). ideal value: 0 lsb. figure 5-109. offset error gnd vcc pc5 (adc5/scl) pc4 (adc4/sda) pc3 (adc3) pc2 (adc2) pc1 (adc1) analog ground plane pc0 (adc0) adc7 adc8 aref gnd 100nf 10h avcc pb5 offset error output code ideal adc actual adc v ref input voltage
235 ata6614q [datasheet] 9240h?auto?10/14 gain error: after adjusting for offset, the gain error is foun d as the deviation of the last transition (0x3fe to 0x3ff) compared to the ideal transition (at 1.5 lsb below maximum). ideal value: 0 lsb figure 5-110. gain error integral non-linearity (inl): after adju sting for offset and gain error, the in l is the maximum deviation of an actual transition compared to an ideal transition for any code. ideal value: 0 lsb. figure 5-111. integral non-linearity (inl) output code ideal adc actual adc v ref input voltage gain error output code ideal adc inl actual adc v ref input voltage
ata6614q [datasheet] 9240h?auto?10/14 236 differential non-linearity (dnl): the maxi mum deviation of the actual code widt h (the interval between two adjacent transitions) from the ideal code width (1 lsb). ideal value: 0 lsb. figure 5-112. differential non-linearity (dnl) quantization error: due to the quantization of the input voltage into a fini te number of codes, a range of input voltages (1 lsb wide) will code to the same value. always 0.5 lsb. absolute accuracy: the maximum deviation of an actual (unadjusted) transition compared to an ideal transition for any code. this is the compound effect of offset, gain error, differential error, non-linearity, and quantization error. ideal value: 0.5 lsb. 5.23.7 adc conversion result after the conversion is complete (adif is high), the conversi on result can be found in the adc result registers (adcl, adch). for single ended conversion, the result is where v in is the voltage on the selected input pin and v ref the selected voltage reference (see table 5-97 on page 238 and table 5-98 on page 238 ). 0x000 represents analog ground, and 0x3ff represents the select ed reference voltage minus one lsb. 5.23.8 temperature measurement the temperature measurement is based on an on-chip temperature sens or that is coupled to a single ended adc input. mux[4..0] bits in admux register enables the temperature se nsor. the internal 1.1v voltage reference must also be selected for the adc voltage reference source in the temper ature sensor measurement. wh en the temperature sensor is enabled, the adc converter can be used in single conversion mode to measure th e voltage over the te mperature sensor. the measured voltage has a linear relationship to the temperature as described in table 5-96 on page 236 . the voltage sensitivity is approximately 1lsb/c and the accuracy of the temperature measurement is 10c using manufacturing calibration values (ts_gain, ts_offset). the values described in table 5-96 on page 236 are typical values. however, due to the process variation the temperature sensor output varies from one chip to another. output code 0x3ff 0x000 0 1 lsb dnl v ref input voltage adc v in 1024 ? v ref ------------------------- = table 5-96. sensor output code vs temperature (typical values) temperature / c -40c +25 c +125 c 0x010d 0x0160 0x01e0
237 ata6614q [datasheet] 9240h?auto?10/14 5.23.8.1 manufacturing calibration calibration values determined during test are available in the signature row. the temperature in degrees celsius can be calculated using the formula: where:. a. adch & adcl are the adc data registers, b. is the temperature sensor gain c. ts_offset is the temperatur e sensor offset correction term ts_gain is the unsigned fixed point 8-bi t temperature sensor gain factor in 1/128th units stored in the signature row. ts_offset is the signed twos complement temperature sensor offset reading stored in the signature row. see table 5-106 on page 257 for signature row parameter address the following code example allows to read signature row data .equ ts_gain = 0x0003 .equ ts_offset = 0x0002 ldi r30,low(ts_gain) ldi r31,high (ts_gain) rcall read_signature_row mov r17,r16 ; save r16 result ldi r30,low(ts_offset) ldi r31,high (ts_offset) rcall read_signature_row ; r16 holds ts_offset and r17 holds ts_gain read_signature_row: in r16,spmcsr ; wait for spmen ready sbrc r16,spmen ; exit loop here when spmcsr is free rjmp read_signature_row ldi r16,((1< ata6614q [datasheet] 9240h?auto?10/14 238 ? bit 5 ? adlar: adc left adjust result the adlar bit affects the presentation of the adc conversion result in the adc data register. write one to adlar to left adjust the result. otherwise, the result is right adjusted. changing the adla r bit will affect the adc data register immediately, regardless of any ongoing conversions. for a complete description of this bit, see section 5.23.9.3 ?adcl and adch ? the adc data register? on page 240 . ? bit 4 ? res: reserved bit this bit is an unused bit in the atmega328p, and will always read as zero. ? bits 3:0 ? mux3:0: analog channel selection bits the value of these bits selects which ana log inputs are connected to the adc. see table 5-98 for details. if these bits are changed during a conversion, the change will not go in effect un til this conversion is complete (adif in adcsra is set). table 5-97. voltage reference selections for adc refs1 refs0 voltage reference selection 0 0 aref, internal v ref turned off 0 1 av cc with external capacitor at aref pin 1 0 reserved 1 1 internal 1.1v voltage reference with external capacitor at aref pin table 5-98. input channel selections mux3..0 single ended input 0000 adc0 0001 adc1 0010 adc2 0011 adc3 0100 adc4 0101 adc5 0110 adc6 0111 adc7 1000 adc8 (1) 1001 (reserved) 1010 (reserved) 1011 (reserved) 1100 (reserved) 1101 (reserved) 1110 1.1v (v bg ) 1111 0v (gnd) note: 1. for temperature sensor.
239 ata6614q [datasheet] 9240h?auto?10/14 5.23.9.2 adcsra ? adc contro l and status register a ? bit 7 ? aden: adc enable writing this bit to one enables the adc. by writing it to zero, the adc is turned o ff. turning the adc off while a conversion i s in progress, will terminate this conversion. ? bit 6 ? adsc: adc start conversion in single conversion mode, write this bit to one to start each conversion. in free runni ng mode, write this bit to one to start the first conversion. the first conversion after adsc has been writt en after the adc has been enabled, or if adsc is written at the same time as the adc is enabled, will take 25 adc clock cycles instead of the normal 13. this first conversion performs initialization of the adc. adsc will read as one as long as a conversion is in progress. when the conversion is complete, it returns to zero. writing zero to this bit has no effect. ? bit 5 ? adate: adc auto trigger enable when this bit is written to one, auto tr iggering of the adc is enabled . the adc will start a conversion on a positive edge of the selected trigger signal. the trigger s ource is selected by setting the adc trigger select bits, adts in adcsrb. ? bit 4 ? adif: adc interrupt flag this bit is set when an adc conversion completes and th e data registers are updated. the adc conversion complete interrupt is executed if the adie bit and the i-bit in sreg are set. adif is cleared by hardware when executing the corresponding interrupt handling vector. alter natively, adif is cleared by writing a logical one to the flag. beware that if doing a read-modify-write on adcsra, a pending interrupt can be di sabled. this also applies if the sbi and cbi instructions are used. ? bit 3 ? adie: adc interrupt enable when this bit is written to one and the i-bit in sreg is set, the adc conversion comp lete interrupt is activated. ? bits 2:0 ? adps2:0: adc prescaler select bits these bits determine the division factor between the system clock frequency and the input clock to the adc. bit 76543210 (0x7a) aden adsc adate adif adie adps2 adps1 adps0 adcsra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 table 5-99. adc prescaler selections adps2 adps1 adps0 division factor 0 0 0 2 0 0 1 2 0 1 0 4 0 1 1 8 1 0 0 16 1 0 1 32 1 1 0 64 1 1 1 128
ata6614q [datasheet] 9240h?auto?10/14 240 5.23.9.3 adcl and adch ? the adc data register 5.23.9.4 adlar = 0 5.23.9.5 adlar = 1 when an adc conversion is complete, the result is found in these two registers. when adcl is read, the adc data register is not updated until adch is read. consequ ently, if the result is left adjusted and no more than 8-bit precision is required, it is sufficient to read adch. otherwis e, adcl must be read first, then adch. the adlar bit in admux, and the muxn bits in admux affect the way the result is read from the registers. if adlar is set, the result is left adjusted. if adlar is clea red (default), the result is right adjusted. ? adc9:0: adc conversion result these bits represent the result fr om the conversion, as detailed in section 5.23.7 ?adc conversion result? on page 236 . bit 151413121110 9 8 (0x79) ? ? ? ? ? ? adc9 adc8 adch (0x78) adc7 adc6 adc5 adc4 adc3 adc2 adc1 adc0 adcl 76543210 read/writerrrrrrrr rrrrrrrr initial value00000000 00000000 bit 151413121110 9 8 (0x79) adc9 adc8 adc7 adc6 adc5 adc4 adc3 adc2 adch (0x78) adc1 adc0 ? ? ? ? ? ? adcl 76543210 read/writerrrrrrrr rrrrrrrr initial value00000000 00000000
241 ata6614q [datasheet] 9240h?auto?10/14 5.23.9.6 adcsrb ? adc contro l and status register b ? bit 7, 5:3 ? res: reserved bits these bits are reserved for future use. to ensure compatibility wi th future devices, these bits must be written to zero when adcsrb is written. ? bit 2:0 ? adts2:0: adc auto trigger source if adate in adcsra is written to one, t he value of these bits selects which source will trigger an adc conversion. if adate is cleared, the adts2:0 settings will have no effect. a conversion will be trigger ed by the rising edge of the selected interru pt flag. note that switching from a trigger s ource that is cleared to a trigger source that is set, will generate a positive edge on the trigger signal. if aden in adcsra is set, this will start a conversion. switching to free running mode (adts[2:0]=0) will not cause a trigger event, even if the adc interrupt flag is set. 5.23.9.7 didr0 ? digital input disable register 0 ? bits 7:6 ? res: reserved bits these bits are reserved for future use. to ensure compatibility wi th future devices, these bits must be written to zero when didr0 is written. ? bit 5:0 ? adc5d..adc0d: adc5 ..0 digital input disable when this bit is written logic one, the digital input buffer on the corresponding adc pin is disabled. the corresponding pin register bit will always read as zero when this bit is set. wh en an analog signal is applied to the adc5..0 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer . note that adc pins adc7 and adc6 do not have digital input bu ffers, and therefore do not require digital input disable bits. bit 76543210 (0x7b) ? acme ? ? ? adts2 adts1 adts0 adcsrb read/write r r/w r r r r/w r/w r/w initial value00000000 table 5-100. adc auto tr igger source selections adts2 adts1 adts0 trigger source 0 0 0 free running mode 0 0 1 analog comparator 0 1 0 external interrupt request 0 0 1 1 timer/counter0 compare match a 1 0 0 timer/counter0 overflow 1 0 1 timer/counter1 compare match b 1 1 0 timer/counter1 overflow 1 1 1 timer/counter1 capture event bit 76543210 (0x7e) ? ? adc5d adc4d adc3d adc2d adc1d adc0d didr0 read/write r r r/w r/w r/w r/w r/w r/w initial value00000000
ata6614q [datasheet] 9240h?auto?10/14 242 5.24 debugwire on-chip debug system 5.24.1 features complete program flow control emulates all on-chip functions, both digital and analog, except reset pin real-time operation symbolic debugging support (both at c and assembler source level, or for other hlls) unlimited number of program break points (using software break points) non-intrusive operation electrical characteristics identical to real device automatic configuration system high-speed operation programming of non-volatile memories 5.24.2 overview the debugwire on-chip debug system uses a one-wire, bi-direc tional interface to control the program flow, execute avr ? instructions in the cpu and to progra m the different non-volatile memories. 5.24.3 physical interface when the debugwire enable (dwen) fuse is programm ed and lock bits are unprogrammed, the debugwire system within the target device is activated. the reset port pin is co nfigured as a wire-and (open-drain) bi-directional i/o pin with pull-up enabled and becomes the communication gateway between target and emulator. figure 5-113. the debugwire setup figure 5-113 shows the schematic of a target mcu, with debugwir e enabled, and the emulator connector. the system clock is not affected by debugwire and will always be the clock source selected by the cksel fuses. when designing a system where debugwire will be used, the following observations must be made for correct operation: pull-up resistors on the dw/(reset) line must not be smaller than 10k . the pull-up resistor is not required for debugwire functionality. connecting the reset pin directly to v cc will not work. capacitors connected to the reset pin must be disconnected when using debugwire. all external reset sources must be disconnected. gnd 1.8 - 5.5v dw vcc dw(reset)
243 ata6614q [datasheet] 9240h?auto?10/14 5.24.4 software break points debugwire supports program memory break points by the avr ? break instruction. setting a break point in avr studio ? will insert a break instruction in the program memory. the in struction replaced by the break instruction will be stored. when program execution is continued, the stored instruction will be exec uted before continuing from the program memory. a break can be inserted manually by putti ng the break instruction in the program. the flash must be re-programmed each time a break point is changed. this is automatically handled by avr studio through the debugwire interface. the use of brea k points will therefore reduce the flash data retention. devices used for debugging purposes should not be shipped to end customers. 5.24.5 limitations of debugwire the debugwire communicatio n pin (dw) is physically located on the same pi n as external reset (reset ). an external reset source is therefore not support ed when the debugwire is enabled. a programmed dwen fuse enables some parts of the clock system to be running in all sleep modes. this will increase the power consumption while in sleep. thus, the dwen fuse should be disabled when debugwire is not used. 5.24.6 register description the following section describes th e registers used with the debugwire. 5.24.6.1 dwdr ? debugwire data register the dwdr register provides a communication channel from the running program in the mcu to the debugger. this register is only accessible by the debugwire and can therefore not be used as a general purpose regist er in the normal operations. 5.25 self-programming the flash, atmega328p 5.25.1 overview in atmega328p, there is no read-while-write support, and no separate boot loader section. the spm instruction can be executed from the entire flash. the device provides a self-programming mechanism for down loading and uploading program code by the mcu itself. the self-programming can use any available dat a interface and associated protocol to read code and write (program) that code into the program memory. the program memory is updated in a page by page fashion. before programming a page with the data stored in the temporary page buffer, the page must be erased. the temporary page buffer is filled one word at a time using spm and the buffer can be filled either before the page erase command or between a pag e erase and a page write operation: alternative 1, fill the buffer before a page erase fill temporary page buffer perform a page erase perform a page write alternative 2, fill the buffer after page erase perform a page erase fill temporary page buffer perform a page write bit 76543210 dwdr[7:0] dwdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
ata6614q [datasheet] 9240h?auto?10/14 244 if only a part of the page needs to be changed, the rest of the page must be st ored (for example in the temporary page buffer) before the erase, and then be re-written. when using al ternative 1, the boot loader provides an effective read-modify- write feature which allows the user software to first read the page, do the necessary c hanges, and then write back the modified data. if alternative 2 is used, it is not possible to read the old data while loading since the page is already erased . the temporary page buffer can be accessed in a random sequence. it is essential that the page address used in both the page erase and page write operation is addressing the same page. 5.25.1.1 performing page erase by spm to execute page erase, set up the address in the z-pointer , write ?00000011? to spmcsr a nd execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage in the z-register. other bits in the z-pointe r will be ignored during this operation. the cpu is halted during the page erase operation. 5.25.1.2 filling the tempor ary buffer (page loading) to write an instruction word, set up the address in the z- pointer and data in r1:r0, write ?00000001? to spmcsr and execute spm within four clock cycles after writing spmcsr. t he content of pcword in the z-register is used to address the data in the temporary buffer. the te mporary buffer will auto-erase after a page write operation or by writing the rwwsre bit in spmcsr. it is also erased after a system reset. no te that it is not possible to write more than one time to each address without erasing the temporary buffer. if the eeprom is written in the middle of an spm page load operation, all data loaded will be lost. 5.25.1.3 performing a page write to execute page write, set up the address in the z-pointer, write ?00000101? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignore d. the page address must be written to pcpage. other bits in the z-pointer must be written to zero during this operation. the cpu is halted during the page write operation. 5.25.2 addressing the flash during self-programming the z-pointer is used to address the spm commands. since the flash is organized in pages (see table 5-119 on page 265 ), the program counter can be treated as having two different sections. one section, consisting of the least significant bits, is addre ssing the words within a page, while the mos t significant bits are addressing the pages. this is shown in figure 5-117 on page 254 . note that the page erase and page write operations are addressed independently. therefore it is of majo r importance that the software addresses the same page in both the page erase and page write operation. the lpm instruction uses the z-pointer to store the address. since this instruction addresses the flash byte-by-byte, also the lsb (bit z0) of the z-pointer is used. bit 151413121110 9 8 zh (r31) z15 z14 z13 z12 z11 z10 z9 z8 zl (r30) z7 z6 z5 z4 z3 z2 z1 z0 76543210
245 ata6614q [datasheet] 9240h?auto?10/14 figure 5-114. addressing the flash during spm (1) note: 1. the different variables used in figure 5-117 are listed in table 5-119 on page 265 . 5.25.2.1 eeprom write pre vents writing to spmcsr note that an eeprom write operation will block all software programming to flash. reading the fuses and lock bits from software will also be prevented during the eeprom write operati on. it is recommended that t he user checks the status bit (eepe) in the eecr register and veri fies that the bit is cleared befo re writing to the spmcsr register. 5.25.2.2 reading the fuse and lock bits from software it is possible to read both the fuse and lock bits from soft ware. to read the lock bits, load the z-pointer with 0x0001 and set the blbset and selfprgen bits in spmcsr. when an lpm in struction is executed withi n three cpu cycles after the blbset and selfprgen bits are set in spmcsr, the value of the lock bits will be loaded in the destination register. the blbset and selfprgen bits will auto-clear upon completion of reading the lock bits or if no lpm instruction is executed within three cpu cycles or no spm instruction is execut ed within four cpu cycles. when blbset and selfprgen are cleared, lpm will work as described in the instruction set manual. the algorithm for reading the fuse low byte is similar to the one described above for reading the lock bits. to read the fuse low byte, load the z-pointer with 0x0000 and set the blbset and selfprgen bits in spmcsr. when an lpm instruction is executed within th ree cycles after the blbset and sel fprgen bits are set in the spmc sr, the value of the fuse low byte (flb) will be loaded in the desti nation register as shown below.see table 5-115 on page 264 for a detailed description and mapping of the fuse low byte. similarly, when reading the fuse high byte (fhb), load 0x0003 in the z-pointer. when an lpm instruction is executed within three cycles after the blbset and selfprgen bits are set in the spmcsr, the va lue of the fuse high byte will be loaded in the destination register as shown below. see table 5-114 on page 263 for detailed description and mapping of the extended fuse byte. similarly, when reading the extended fuse byte (efb), load 0x0002 in the z-pointer. when an lpm instruction is executed within three cycles after the blbset and selfprgen bits are se t in the spmcsr, the value of the extended fuse byte will bit pagemsb pcmsb zpagemsb zpcmsb 0 1 15 z-register program counter word address within page page address within the flash 0 pcword pcpage 02 01 00 pageend pcword[pagemsb:0] page program memory instructions word page bit 76543210 rd ??????lb2lb1 bit 76543210 rd flb7 flb6 flb5 flb4 flb3 flb2 flb1 flb0 bit 76543210 rd fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0
ata6614q [datasheet] 9240h?auto?10/14 246 be loaded in the destination register as shown below. see table 5-115 on page 264 for detailed description and mapping of the extended fuse byte. fuse and lock bits that are programmed, will be read as zero . fuse and lock bits that are unprogrammed, will be read as one. 5.25.2.3 preventing flash corruption during periods of low v cc , the flash program can be corrupted because th e supply voltage is too low for the cpu and the flash to operate properly. these issues are the same as for board level systems using the flash, and the same design solutions should be applied. a flash program corruption can be caused by two situations wh en the voltage is too low. firs t, a regular write sequence to the flash requires a minimum voltage to operate correctly. second ly, the cpu itself can execute instructions incorrectly, if th e supply voltage for executing instructions is too low. flash corruption can easily be avoided by followin g these design recommendations (one is sufficient): 1. keep the avr reset active (low) during periods of in sufficient power supply voltage. this can be done by enabling the internal brown-out detector (bod) if the o perating voltage matches the detection level. if not, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. 2. keep the avr core in power-down sleep mode during periods of low v cc . this will prevent the cpu from attempt- ing to decode and execute instructions, effectively prot ecting the spmcsr register and thus the flash from unintentional writes. 5.25.2.4 programming time for flash when using spm the calibrated rc oscillator is used to time flash accesses. table 5-107 shows the typical programming time for flash accesses from the cpu. bit 76543210 rd fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0 table 5-101. spm programming time (1) symbol min programming time max programming time flash write (page erase, page write, and write lock bits by spm) 3.7ms 4.5ms note: 1. minimum and maximum programming time is per individual operation.
247 ata6614q [datasheet] 9240h?auto?10/14 5.25.2.5 simple assembly code example for a boot loader note that the rwwsb bit will always be read as zero in atme ga328p. nevertheless, it is recommended to check this bit as shown in the code example, to ensure compatib ility with devices supporting read-while-write. ;-the routine writes one page of data from ram to flash ; the first data location in ram is pointed to by the y pointer ; the first data location in flash is pointed to by the z-pointer ;-error handling is not included ;-the routine must be placed inside the boot space ; (at least the do_spm sub routine). only code inside nrww section can ; be read during self-programming (page erase and page write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-it is assumed that either the interrupt table is moved to the boot ; loader section or that the interrupts are disabled. .equ pagesizeb = pagesize*2;pagesizeb is page size in bytes, not words .org smallbootstart write_page: ; page erase ldi spmcrval, (1< ata6614q [datasheet] 9240h?auto?10/14 248 rdloop: lpm r0, z+ ld r1, y+ cpse r0, r1 rjmp error sbiw loophi:looplo, 1 ;use subi for pagesizeb<=256 brne rdloop ; return to rww section ; verify that rww section is safe to read return: in temp1, spmcsr sbrs temp1, rwwsb ; if rwwsb is set, the rww section is not ready yet ret ; re-enable the rww section ldi spmcrval, (1< 249 ata6614q [datasheet] 9240h?auto?10/14 5.25.3 register description 5.25.3.1 spmcsr ? store program memory control and status register the store program memory control and status register contai ns the control bits needed to control the program memory operations. ? bit 7 ? spmie: spm interrupt enable when the spmie bit is written to one, and the i-bit in the stat us register is set (one), the spm ready interrupt will be enable d. the spm ready interrupt will be executed as long as the selfp rgen bit in the spmcsr register is cleared. the interrupt will not be generated during eeprom write or spm. ? bit 6 ? rwwsb: read-while-write section busy this bit is for compatibility with de vices supporting read-while-write. it will always read as zero in atmega328p. ? bit 5 ? res: reserved bit this bit is a reserved bit in the atmega328p and will always read as zero. ? bit 4 ? rwwsre: read-while-write section read enable if the rwwsre bit is written while filling the temporary pa ge buffer, the temporary page buffer will be cleared and the data will be lost. ? bit 3 ? blbset: boot lock bit set an lpm instruction within three cycles after blbset and selfprgen are set in the spmcsr register, will read either the lock bits or the fuse bits (depending on z0 in the z-pointer) into the destination register. see section 5.25.2.2 ?reading the fuse and lock bits from software? on page 245 for details. ? bit 2 ? pgwrt: page write if this bit is written to one at the same time as selfprgen, the next spm in struction within four cl ock cycles executes page write, with the data stored in the temporary buffer. the page address is taken fr om the high part of the z-pointer. the data in r1 and r0 are ignored. the pgwrt bit will auto-clear upon comple tion of a page write, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire p age write operation. ? bit 1 ? pgers: page erase if this bit is written to one at the same time as selfprgen, the next spm in struction within four cl ock cycles executes page erase. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgers bit will auto-clear upon completion of a page erase, or if no spm instru ction is executed within four cl ock cycles. the cpu is halted during the entire pag e write operation. ? bit 0 ? selfprgen: self programming enable this bit enables the spm instruction for the next four clock cy cles. if written to one together with either rwwsre, blbset, pgwrt, or pgers, the following spm instruction will have a special meaning, see description above. if only selfprgen is written, the following spm instruction will store the value in r1:r0 in the te mporary page buffer addressed by the z- pointer. the lsb of the z-pointer is ignored. the selfprgen bit will auto-clear upon completion of an spm instruction, or if no spm instruction is exec uted within four clock cycles. during page er ase and page write, the selfprgen bit remains high until the operation is completed. writing any other combination than ?10001?, ?01001?, ?00101?, ?00011 ? or ?00001? in the lower five bits will have no effect. bit 7 6 5 4 3 2 1 0 0x37 (0x57) spmie rwwsb ? rwwsre blbset pgwrt pgers selfprgen spmcsr read/write r/w r r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
ata6614q [datasheet] 9240h?auto?10/14 250 5.26 boot loader support ? read-while-write self-programming 5.26.1 features read-while-write self-programming flexible boot memory size high security (separate boot lock bits for a flexible protection) separate fuse to select reset vector optimized page (1) size code efficient algorithm efficient read-modify-write support note: 1. a page is a section in the flash consisting of several bytes (see table 5-119 on page 265 ) used during program- ming. the page organization does not affect normal operation. 5.26.2 overview the boot loader support provides a real read-while-write self-programming mechanism for downloading and uploading program code by the mcu itself. this feature allows flexible application software updates controlled by the mcu using a flash-resident boot loader program. the b oot loader program can use any available data interface and associated protocol to read code and write (program) that code into the flash memory , or read the code from the program memory. the program code within the boot loader section has the capability to write into the entire flash, including the boot loader memory. the boot loader can thus even modify itself, and it can also erase it self from the code if the feat ure is not needed anymore. the size of the boot loader memory is configurable with fuses and th e boot loader has two separate sets of boot lock bits which can be set independently. this gives the user a unique fl exibility to select different levels of protection. 5.26.3 application and boot loader flash sections the flash memory is organized in two main sections, th e application section and the boot loader section (see figure 5-116 ). the size of the different sections is conf igured by the bootsz fuses as shown in figure 5-116 . these two sections can have different level of protection since they have different sets of lock bits. 5.26.3.1 applic ation section the application section is the section of the flash that is used for storing the app lication code. the protection level for the application section can be selected by the app lication boot lock bits (boot lock bits 0), see table 5-103 on page 253 . the application section can never st ore any boot loader code since the spm instru ction is disabled when executed from the application section. 5.26.3.2 bls ? boot loader section while the application section is used for st oring the application code, the the boot loader software must be located in the bls since the spm instruction can initiate a programming w hen executing from the bls only. the spm instruction can access the entire flash, including the bls itself. the protection level fo r the boot loader section ca n be selected by the boot loader lock bits (boot lock bits 1), see table 5-104 on page 253 . 5.26.4 read-while-write and no read-while-write flash sections whether the cpu supports read-while-write or if the cpu is halted during a boot loader software update is dependent on which address that is being programmed. in addition to the two sections that are configurable by the bootsz fuses as described above, the flash is also divided into two fixed sect ions, the read-while-write (rww) section and the no read-while- write (nrww) section. the limit between the rww- and nrww sections is given in figure 5-116 on page 252 . the main difference between the two sections is: when erasing or writing a page located inside the rw w section, the nrww section can be read during the operation. when erasing or writing a page located inside the nrww section, the cpu is halted during the entire operation. note that the user software can never re ad any code that is locat ed inside the rww section durin g a boot loader software operation. the syntax ?read-while-write sect ion? refers to which section that is being programmed (erased or written), not which section that actually is being re ad during a boot loader software update.
251 ata6614q [datasheet] 9240h?auto?10/14 5.26.4.1 rww ? read-while-write section if a boot loader software update is programming a page inside th e rww section, it is possible to read code from the flash, but only code that is located in the nrww section. during an on-going programming, the software must ensure that the rww section never is being read. if the user software is trying to read code that is located inside the rww section (i.e., by a call/jmp/lpm or an interrupt) during programming, the softwar e might end up in an unknown state. to avoid this, the interrupts should either be disabled or mo ved to the boot loader section. the boot loader section is always located in the nrww section. the rww section busy bit (rwwsb) in the stor e program memory control and status register (spmcsr) will be read as logical one as long as the rww section is blocked for reading. after a programming is completed, the rwwsb must be cleared by software before reading code located in the rww section. see section 5.26.9.1 ?spmcsr ? store program memory control and status register? on page 261 for details on how to clear rwwsb. 5.26.4.2 nrww ? no read-while-write section the code located in the nrww section can be read when the boo t loader software is updating a page in the rww section. when the boot loader code updates the nrww section, the cpu is halted during the entire page erase or page write operation. figure 5-115. read-while-write versus no read-while-write table 5-102. read-while-write features which section does the z-pointer address during the programming? which section can be read during programming? cpu halted? read-while-write supported? rww section nrww section no yes nrww section none yes no z-pointer addresses rww section code located in nrww section can be read during the operation z-pointer addresses nrww section cpu is halted during the operation read-while-write (rww) section no read-while-write (rww) section
ata6614q [datasheet] 9240h?auto?10/14 252 figure 5-116. memory sections 5.26.5 boot loader lock bits if no boot loader capability is needed, the entire flash is available for application code. the boot loader has two separate se ts of boot lock bits which can be set independent ly. this gives the user a unique flexibility to select differen t levels of protec tion. the user can select: to protect the entire flash from a software update by the mcu. to protect only the boot loader flash se ction from a software update by the mcu. to protect only the application flash se ction from a software update by the mcu. allow software update in the entire flash. see table 5-103 and table 5-104 for further details. the boot lock bits can be set in software and in serial or parallel programming mode, but they can be cleared by a chip eras e command only. the general write lock (lock bit mode 2) does not control the programmi ng of the flash memory by spm in struction. similarly, the general read/write lock (lock bit mode 1) does not control reading nor writing by lpm/spm, if it is attempted. program memory bootsz = 11 0x0000 flashend read-while-write section no read-while- write section end rww start nrww end application start boot loader program memory bootsz = 10 0x0000 flashend read-while-write section no read-while- write section end rww start nrww end application start boot loader program memory bootsz = 01 0x0000 flashend read-while-write section no read-while- write section end rww start nrww end application start boot loader program memory bootsz = 00 0x0000 flashend read-while-write section no read-while- write section end rww, end application start rww, start boot loader application flash section application flash section boot loader flash section boot loader flash section application flash section application flash section boot loader flash section application flash section application flash section boot loader flash section application flash section
253 ata6614q [datasheet] 9240h?auto?10/14 5.26.6 entering the boot loader program entering the boot loader takes place by a jump or call from the application program. this may be initiated by a trigger such as a command received via usart, or spi interface. alternativ ely, the boot reset fuse can be programmed so that the reset vector is pointing to the boot flash start address after a reset. in this case, the boot loader is started after a reset. after the application code is loaded, the program c an start executing the application code. no te that the fuses cannot be changed by the mcu itself. this means that once the b oot reset fuse is programmed, the reset ve ctor will always point to the boot loader reset and the fuse can only be changed through the serial or parallel programming interface. table 5-103. boot lock bit0 protecti on modes (application section) (1) blb0 mode blb02 blb01 protection 1 1 1 no restrictions for spm or lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 3 0 0 spm is not allowed to write to the application section, and lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 4 0 1 lpm executing from the boot loader sect ion is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. note: 1. ?s unpr1? unprogramm ed, ?0? means programmed. table 5-104. boot lock bit1 protecti on modes (boot loader section) (1) blb1 mode blb12 blb11 protection 1 1 1 no restrictions for spm or lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 3 0 0 spm is not allowed to write to the b oot loader section, and lpm executing from the application section is not al lowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing fr om the boot loader section. 4 0 1 lpm executing from the app lication section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while execut ing from the boot loader section. note: 1. ?1? means unprogra mmed, ?0? means programmed table 5-105. boot reset fuse (1) bootrst reset address 1 reset vector = application reset (address 0x0000) 0 reset vector = boot loader reset note: 1. ?1? means unprogra mmed, ?0? means programmed
ata6614q [datasheet] 9240h?auto?10/14 254 5.26.7 addressing the flash during self-programming the z-pointer is used to address the spm commands. since the flash is organized in pages (see table 5-119 on page 265 ), the program counter can be treated as having two different sections. one section, consisting of the least significant bits, is addre ssing the words within a page, while the mos t significant bits are addressing the pages. this is1 shown in figure 5-117 . note that the page erase and page write operations are addressed independently. ther efore it is of major importance that the boot loader software addresses the same page in both the page erase and page write operation. once a programming operation is initiated, the address is latched and the z-pointer can be used for other operations. the only spm operation that does not use t he z-pointer is setting the boot loader lo ck bits. the content of the z-pointer is ignored and will have no effect on the operat ion. the lpm instruction does also use the z-pointer to store the address. since this instruction addresses the flash byte-by-byte, al so the lsb (bit z0) of the z-pointer is used. figure 5-117. addressing the flash during spm bit 151413121110 9 8 zh (r31) z15 z14 z13 z12 z11 z10 z9 z8 zl (r30) z7 z6 z5 z4 z3 z2 z1 z0 76543210 bit pagemsb pcmsb zpagemsb zpcmsb 0 1 15 z-register program counter word address within page page address within the flash 0 pcword pcpage 02 01 00 pageend pcword[pagemsb:0] page program memory instructions word page
255 ata6614q [datasheet] 9240h?auto?10/14 5.26.8 self-programming the flash the program memory is updated in a page by page fashion. before programming a page with the data stored in the temporary page buffer, the page must be erased. the temporary page buffer is filled one word at a time using spm and the buffer can be filled either before the page erase command or between a pag e erase and a page write operation: alternative 1, fill the buffer before a page erase fill temporary page buffer perform a page erase perform a page write alternative 2, fill the buffer after page erase perform a page erase fill temporary page buffer perform a page write if only a part of the page needs to be changed, the rest of the page must be st ored (for example in the temporary page buffer) before the erase, and then be rewritten. when using alte rnative 1, the boot loader prov ides an effective read-modify- write feature which allows the user software to first read the page, do the necessary c hanges, and then write back the modified data. if alternative 2 is used, it is not possible to read the old data while loading since the page is already erased . the temporary page buffer can be accessed in a random sequence. it is essential that the page address used in both the page erase and page write operation is addressing the same page. see section 5.26.8.13 ?simple assembly code example for a boot loader? on page 258 for an assembly code example. 5.26.8.1 performing page erase by spm to execute page erase, set up the address in the z-pointer , write ?x0000011? to spmcsr and execute spm within four clock cycles after writing spmcsr. the dat a in r1 and r0 is ignored. the page a ddress must be written to pcpage in the z-register. other bits in the z-pointe r will be ignored during this operation. page erase to the rww section: the nrww section can be read during the page erase. page erase to the nrww section: the cpu is halted during the operation. 5.26.8.2 filling the tempor ary buffer (page loading) to write an instruction word, set up the address in the z- pointer and data in r1:r0, write ?00000001? to spmcsr and execute spm within four clock cycles after writing spmcsr. t he content of pcword in the z-register is used to address the data in the temporary buffer. the te mporary buffer will auto-erase after a pag e write operation or by writing the rwwsre bit in spmcsr. it is also erased after a system reset. no te that it is not possible to write more than one time to each address without erasing the temporary buffer. if the eeprom is written in the middle of an spm page load operation, all data loaded will be lost. 5.26.8.3 performing a page write to execute page write, set up the address in the z-pointer, write ?x0000101? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignore d. the page address must be written to pcpage. other bits in the z-pointer must be written to zero during this operation. page write to the rww section: the nrww section can be read during the page write. page write to the nrww section: t he cpu is halted during the operation. 5.26.8.4 using the spm interrupt if the spm interrupt is enabled, the spm interrupt will generat e a constant interrupt when the selfprgen bit in spmcsr is cleared. this means that the interrupt can be used instead of polling the spmcsr register in software. when using the spm interrupt, the interru pt vectors should be move d to the bls section to avoid that an interrupt is accessi ng the rww section when it is blocked for reading. how to move the interrupts is described in section 5.11 ?interrupts? on page 73 . 5.26.8.5 consideration while updating bls special care must be taken if the user allows the boot loader section to be updated by leaving boot lock bit11 unprogrammed. an accidental write to the boot loader itself can corrupt the entire boot loader, and further software updates might be impossible. if it is not necessary to change the boot loader software itse lf, it is recommended to program the boot lock bit11 to protect the boot loader softw are from any internal software changes.
ata6614q [datasheet] 9240h?auto?10/14 256 5.26.8.6 prevent reading the rww section during self-programming during self-programming (either page erase or page write) , the rww section is always blocked for reading. the user software itself must prevent that this section is addressed during the self programming operation. the rwwsb in the spmcsr will be set as long as the rww section is busy. duri ng self-programming the interrupt vector table should be moved to the bls as described in section 5.10.8 ?watchdog timer? on page 68 , or the interrupts must be disabled. before addressing the rww section after the programming is completed, the user software must clear the rwwsb by writing the rwwsre. see section 5.26.8.13 ?simple assembly code example for a boot loader? on page 258 for an example. 5.26.8.7 setting the boot loader lock bits by spm to set the boot loader lock bits and general lock bits, write the desired data to r0, write ?x0001001? to spmcsr and execute spm within four clock cycles after writing spmcsr. see table 5-103 and table 5-104 for how the different settings of the boot loader bits affect the flash access. if bits 5..0 in r0 are cleared (zero), the corresponding lock bit will be programmed if an spm instruction is executed within four cycles after blbset and selfprgen are set in spmcsr. the z-pointer is don?t care during this operation, but for future compatibility it is recommended to load the z-pointer with 0x0001 (same as used for reading the lo ck bits). for future compatibility it is also recommended to set bits 7 and 6 in r0 to ?1? when writing the lock bits. when programming the lock bits the entire flash can be read during the operation. 5.26.8.8 eeprom write pre vents writing to spmcsr note that an eeprom write operation will block all software programming to flash. reading the fuses and lock bits from software will also be prevented during the eeprom write operati on. it is recommended that t he user checks the status bit (eepe) in the eecr register and veri fies that the bit is cleared befo re writing to the spmcsr register. 5.26.8.9 reading the fuse and lock bits from software it is possible to read both the fuse and lock bits from soft ware. to read the lock bits, load the z-pointer with 0x0001 and set the blbset and selfprgen bits in spmcsr. when an lpm in struction is executed withi n three cpu cycles after the blbset and selfprgen bits are set in spmcsr, the value of the lock bits will be loaded in the destination register. the blbset and selfprgen bits will auto-clear upon completion of reading the lock bits or if no lpm instruction is executed within three cpu cycles or no spm instruction is execut ed within four cpu cycles. when blbset and selfprgen are cleared, lpm will work as described in the instruction set manual. the algorithm for reading the fuse low byte is similar to the one described above for reading the lock bits. to read the fuse low byte, load the z-pointer with 0x0000 and set the blbset and selfprgen bits in spmcsr. when an lpm instruction is executed within th ree cycles after the blbset and sel fprgen bits are set in the spmc sr, the value of the fuse low byte (flb) will be loaded in the destinati on register as shown below. refer to table 5-115 on page 264 for a detailed description and mapping of the fuse low byte. similarly, when reading the fuse high byte, load 0x0003 in the z-pointer. when an lpm instruction is executed within three cycles after the blbset and selfprgen bits are set in the sp mcsr, the value of the fuse high byte (fhb) will be loaded in the destination register as shown below. refer to table 5-117 on page 265 for detailed description and mapping of the fuse high byte. bit 76543210 r0 1 1 blb12 blb11 blb02 blb01 lb2 lb1 bit 76543210 rd ? ? blb12 blb11 blb02 blb01 lb2 lb1 bit 76543210 rd flb7 flb6 flb5 flb4 flb3 flb2 flb1 flb0 bit 76543210 rd fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0
257 ata6614q [datasheet] 9240h?auto?10/14 when reading the extended fuse byte, load 0x0002 in the z-poin ter. when an lpm instruction is executed within three cycles after the blbset and selfprgen bits are se t in the spmcsr, the value of the extended fuse byte (efb) will be loaded in the destination register as shown below. refer to table 5-114 on page 263 for detailed description and mapping of the extended fuse byte. fuse and lock bits that are programmed, will be read as zero . fuse and lock bits that are unprogrammed, will be read as one. 5.26.8.10 reading the signature row from software to read the signature row from software, load the z-pointer with the signature byte address given in table 5-106 on page 257 and set the sigrd and spmen bits in spmcsr. when an lpm instruction is executed within three cpu cycles after the sigrd and spmen bits are set in spmcs r, the signature byte value will be loa ded in the destination register. the sigrd and spmen bits will auto-clear upon completion of readi ng the signature row lock bits or if no lpm instruction is executed within three cpu cycles. when si grd and spmen are cleared, lpm will work as described in the instruction set manual. 5.26.8.11 preventing flash corruption during periods of low v cc , the flash program can be corrupted because th e supply voltage is too low for the cpu and the flash to operate properly. these issues are the same as for board level systems using the flash, and the same design solutions should be applied. a flash program corruption can be caused by two situations wh en the voltage is too low. firs t, a regular write sequence to the flash requires a minimum voltage to operate correctly. second ly, the cpu itself can execute instructions incorrectly, if th e supply voltage for executing instructions is too low. flash corruption can easily be avoided by followin g these design recommendations (one is sufficient): 1. if there is no need for a boot loader update in the system, program the boot loader lock bits to prevent any boot loader software updates. 2. keep the avr ? reset active (low) during periods of insuffic ient power supply voltag e. this can be done by enabling the internal brown-out detector (bod) if the o perating voltage matches the detection level. if not, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write operation will be completed provided that the power supply voltage is sufficient. 3. keep the avr core in power-down sleep mode during periods of low v cc . this will prevent the cpu from attempt- ing to decode and execute instructions, effectively prot ecting the spmcsr register and thus the flash from unintentional writes. bit 76543210 rd ? ? ? ? efb3 efb2 efb1 efb0 table 5-106. signature row addressing signature byte z-pointer address device signature byte 1 0x0000 device signature byte 2 0x0002 device signature byte 3 0x0004 rc oscillator calibration byte 0x0001 tsoffset - temp sensor offset 0x0002 tsgain - temp sensor gain 0x0003 note: all other addresses are reserved for future use.
ata6614q [datasheet] 9240h?auto?10/14 258 5.26.8.12 programming time for flash when using spm the calibrated rc oscillator is used to time flash accesses. table 5-107 shows the typical programming time for flash accesses from the cpu. 5.26.8.13 simple assembly code example for a boot loader ;-the routine writes one page of data from ram to flash ; the first data location in ram is pointed to by the y pointer ; the first data location in flash is pointed to by the z-pointer ;-error handling is not included ;-the routine must be placed inside the boot space ; (at least the do_spm sub routine). only code inside nrww section can ; be read during self-programming (page erase and page write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-it is assumed that either the interrupt table is moved to the boot ; loader section or that the interrupts are disabled. .equ pagesizeb = pagesize*2;pagesizeb is page size in bytes, not words .org smallbootstart write_page: ; page erase ldi spmcrval, (1< 259 ata6614q [datasheet] 9240h?auto?10/14 ; read back and check, optional ldi looplo, low(pagesizeb) ;init loop variable ldi loophi, high(pagesizeb) ;not required for pagesizeb<=256 subi yl, low(pagesizeb) ;restore pointer sbci yh, high(pagesizeb) rdloop: lpm r0, z+ ld r1, y+ cpse r0, r1 jmp error sbiw loophi:looplo, 1 ;use subi for pagesizeb<=256 brne rdloop ; return to rww section ; verify that rww section is safe to read return: in temp1, spmcsr sbrs temp1, rwwsb if rwwsb is set, the rww section is not ready yet ret ; re-enable the rww section ldi spmcrval, (1< ata6614q [datasheet] 9240h?auto?10/14 260 5.26.8.14 atmega328p b oot loader parameters in table 5-108 through table 5-110 , the parameters used in the description of the self programming are given. for details about these two section, see section 5.26.4.2 ?nrww ? no read-while-write section? on page 251 and section 5.26.4.1 ?rww ? read-while-wri te section? on page 251 table 5-108. boot size configuration, atmega328p bootsz1 bootsz0 boot size pages application flash section boot loader flash section end application section boot reset address (start boot loader section) 1 1 256 words 4 0x0000 - 0x3eff 0x3f00 - 0x3fff 0x3eff 0x3f00 1 0 512 words 8 0x0000 - 0x3dff 0x3e00 - 0x3fff 0x3dff 0x3e00 0 1 1024 words 16 0x0000 - 0x3bff 0x3c00 - 0x3fff 0x3bff 0x3c00 0 0 2048 words 32 0x0000 - 0x37ff 0x3800 - 0x3fff 0x37ff 0x3800 note: the different bootsz fuse configurations are shown in figure 5-116 on page 252 . table 5-109. read-while-write limit, atmega328p section pages address read-while-write section (rww) 224 0x0000 - 0x37ff no read-while-write section (nrww) 32 0x3800 - 0x3fff table 5-110. explanation of di fferent variables used in figure 5-117 and the mapping to the z-pointer, atmega328p variable corresponding z-value (1) description pcmsb 13 most significant bit in the program counter. (the program counter is 14 bits pc[13:0]) pagemsb 5 most significant bit which is used to address the words within one page (64 words in a page requires 6 bits pc [5:0]) zpcmsb z14 bit in z-register that is map ped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z6 bit in z-register that is mapped to pagemsb. because z0 is not used, the zpagemsb equals pagemsb + 1. pcpage pc[13:6] z14:z7 program counter page address: page select, for page erase and page write pcword pc[5:0] z6:z1 program counter word address: wo rd select, for filling temporary buffer (must be zero during page write operation) note: 1. z15: always ignored z0: should be zero for all spm commands, byte select for the lpm instruction. see section 5.26.7 ?addressing the flash du ring self-programming? on page 254 for details about the use of z-pointer during self-programming.
261 ata6614q [datasheet] 9240h?auto?10/14 5.26.9 register description 5.26.9.1 spmcsr ? store program memory control and status register the store program memory contro l and status register contains the control bits needed to control the boot loader operations. ? bit 7 ? spmie: spm interrupt enable when the spmie bit is written to one, and the i-bit in the stat us register is set (one), the spm ready interrupt will be enable d. the spm ready interrupt will be executed as long as the selfprgen bit in the spmcsr register is cleared. ? bit 6 ? rwwsb: read-while-write section busy when a self-programming (page erase or page write) operati on to the rww section is initiated, the rwwsb will be set (one) by hardware. when the rwwsb bit is set, the rww sect ion cannot be accessed. the rwwsb bit will be cleared if the rwwsre bit is written to one afte r a self-programming operation is completed. alternatively the rwwsb bit will automatically be cleared if a pa ge load operation is initiated. ? bit 5 ? res: reserved bit this bit is a reserved bit in the atmega328p and always read as zero. ? bit 4 ? rwwsre: read-while-write section read enable when programming (page erase or page write) to the rww section, the rww section is blocked for reading (the rwwsb will be set by hardware). to re-enable t he rww section, the user software must wait until the programming is completed (selfprgen will be cleared). then, if the rwwsre bit is written to one at the same time as self prgen, the next spm instruction within four clock cycles re-en ables the rww section. the rww section cannot be re- enabled while the flash is busy with a page erase or a page write (selfprgen is set). if the rwwsre bit is written while the flash is being loaded, the flash load operation will abort and the data loaded will be lost. ? bit 3 ? blbset: boot lock bit set if this bit is written to one at the same time as selfprgen, the next spm instruction within four clock cycles sets boot lock bits and memory lock bits, according to the data in r0. the data in r1 and the address in the z-pointer are ignored. the blbset bit will automatically be cleared upon completion of the lock bit set, or if no spm instruction is executed within four clock cycles. an lpm instruction within three cycles after blbset and selfprgen are set in the spmcsr register, will read either the lock bits or the fuse bits (depending on z0 in the z-pointer) into the destination register. see section 5.26.8.9 ?reading the fuse and lock bits from software? on page 256 for details. ? bit 2 ? pgwrt: page write if this bit is written to one at the same time as selfprgen, the next spm in struction within four cl ock cycles executes page write, with the data stored in the temporary buffer. the page address is taken fr om the high part of the z-pointer. the data in r1 and r0 are ignored. the pgwrt bit will auto-clear upon comple tion of a page write, or if no spm instruction is executed within four clock cycles. the cpu is halte d during the entire page write operation if the nrww section is addressed. ? bit 1 ? pgers: page erase if this bit is written to one at the same time as selfprgen, the next spm in struction within four cl ock cycles executes page erase. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgers bit will auto-clear upon completion of a page erase, or if no spm instru ction is executed within four cl ock cycles. the cpu is halted during the entire page writ e operation if the nrww section is addressed. bit 7 6 5 4 3 2 1 0 0x37 (0x57) spmie rwwsb ? rwwsre blbset pgwrt pgers selfprgen spmcsr read/write r/w r r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
ata6614q [datasheet] 9240h?auto?10/14 262 ? bit 0 ? selfprgen: self programming enable this bit enables the spm instruction for the next four clock cy cles. if written to one together with either rwwsre, blbset, pgwrt or pgers, the following spm inst ruction will have a special meaning, see description above. if only selfprgen is written, the following spm instruction will store the value in r1:r0 in the te mporary page buffer addressed by the z- pointer. the lsb of the z-pointer is ignored. the selfprgen bit will auto-clear upon completion of an spm instruction, or if no spm instruction is executed within four clock cycles. du ring page erase and page write, the selfprgen bit remains high until the operation is completed. writing any other combination than ?10001?, ?01001?, ?00101?, ?00011 ? or ?00001? in the lower five bits will have no effect. 5.27 memory programming 5.27.1 program and data memory lock bits the atmega328p provides six lock bits which can be left unpr ogrammed (?1?) or can be programmed (?0?) to obtain the additional features listed in table 5-112 . the lock bits can only be erased to ?1? with the chip erase command.the atmega328p has no separate boot loader section. the spm inst ruction is enabled for the wh ole flash if the selfprgen fuse is programmed (?0?), otherwise it is disabled. table 5-111. lock bit byte (1) lock bit byte bit no description default value 7 ? 1 (unprogrammed) 6 ? 1 (unprogrammed) blb12 (2) 5 boot lock bit 1 (unprogrammed) blb11 (2) 4 boot lock bit 1 (unprogrammed) blb02 (2) 3 boot lock bit 1 (unprogrammed) blb01 (2) 2 boot lock bit 1 (unprogrammed) lb2 1 lock bit 1 (unprogrammed) lb1 0 lock bit 1 (unprogrammed) notes: 1. ?1? means unprogra mmed, ?0? means programmed 2. only on atmega328p table 5-112. lock bit protection modes (1)(2) memory lock bits protection type lb mode lb2 lb1 1 1 1 no memory lock features enabled. 2 1 0 further programming of the flash and eeprom is disabled in parallel and serial programming mode. the fuse bits are locked in both serial and parallel programming mode (1) . 3 0 0 further programming and verification of the flash and eeprom is disabled in parallel and serial programming mode. the boot lock bits and fuse bits are locked in both serial and parallel programming mode (1) . notes: 1. program the fuse bits and boot lock bits before programming the lb1 and lb2. 2. ?1? means unprogrammed, ?0? means programmed
263 ata6614q [datasheet] 9240h?auto?10/14 5.27.2 fuse bits the atmega328p has three fuse bytes. table 5-114 - table 5-117 describe briefly the functionality of all the fuses and how they are mapped into the fuse bytes. note that the fuse s are read as logical zero, ?0?, if they are programmed. table 5-113. lock bit protection modes (1)(2) blb0 mode blb02 blb01 1 1 1 no restrictions for spm or lpm accessing the application section. 2 1 0 spm is not allowed to writ e to the application section. 3 0 0 spm is not allowed to write to the application section, and lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 4 0 1 lpm executing from the boot loader sect ion is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. blb1 mode blb12 blb11 1 1 1 no restrictions for spm or lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 3 0 0 spm is not allowed to write to the boot loader section, and lpm executing from the application section is not a llowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. 4 0 1 lpm executing from the application sect ion is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. notes: 1. program the fuse bits and boot lock bits before programming the lb1 and lb2. 2. ?1? means unprogrammed, ?0? means programmed table 5-114. extended fuse byte for atmega328p extended fuse byte bit no description default value ? 7 ? 1 ? 6 ? 1 ? 5 ? 1 ? 4 ? 1 ? 3 ? 1 ? 2 ? 1 ? 1 ? 1 selfprgen 0 self programming enable 1 (unprogrammed)
ata6614q [datasheet] 9240h?auto?10/14 264 table 5-115. extended fuse byte for atmega328p extended fuse byte bit no description default value ? 7 ? 1 ? 6 ? 1 ? 5 ? 1 ? 4 ? 1 ? 3 ? 1 bodlevel2 (1) 2 brown-out detector trigger level 1 (unprogrammed) bodlevel1 (1) 1 brown-out detector trigger level 1 (unprogrammed) bodlevel0 (1) 0 brown-out detector trigger level 1 (unprogrammed) note: 1. see table 5-132 on page 281 for bodlevel fuse decoding. table 5-116. fuse high byte for atmega328p high fuse byte bit no description default value rstdisbl (1) 7 external reset disable 1 (unprogrammed) dwen 6 debugwire enable 1 (unprogrammed) spien (2) 5 enable serial program and data downloading 0 (programmed, spi programming enabled) wdton (3) 4 watchdog timer always on 1 (unprogrammed) eesave 3 eeprom memory is preserved through the chip erase 1 (unprogrammed), eeprom not reserved bootsz1 2 select boot size (see table 5-108 on page 260 for details) 0 (programmed) (4) bootsz0 1 select boot size (see table 5-108 on page 260 for details) 0 (programmed) (4) bootrst 0 select reset vector 1 (unprogrammed) notes: 1. see section 5.13.3.2 ?alter nate functions of port c? on page 92 for description of rstdisbl fuse. 2. the spien fuse is not accessible in serial programming mode. 3. see section 5.10.9.2 ?wdtcsr ? watchdog timer control register? on page 71 for details. 4. the default value of bootsz[1:0] results in maximum boot size. see section 5-121 ?pin name mapping? on page 266 .
265 ata6614q [datasheet] 9240h?auto?10/14 the status of the fuse bits is not affected by chip erase. note that the fuse bits are locked if lock bit1 (lb1) is programmed. program the fuse bits before programming the lock bits. 5.27.2.1 latching of fuses the fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves programming mode. this does not ap ply to the eesave fuse which will take effect once it is programmed. the fuses are also latched on power-up in normal mode. 5.27.3 signature bytes all atmel ? microcontrollers have a three-byte signat ure code which identifies the device. th is code can be read in both serial and parallel mode, also when the device is locked. the three bytes reside in a separate address space. for the atmega328p the signature bytes are given in table 5-118 . 5.27.4 calibration byte the atmega328p has a byte calibration value for the internal rc oscillator. this byte resides in the high byte of address 0x000 in the signature address space. during reset, this byte is automatically wr itten into the osccal register to ensure correct frequency of the calibrated rc oscillator. 5.27.5 page size table 5-117. fuse low byte low fuse byte bit no description default value ckdiv8 (4) 7 divide clock by 8 0 (programmed) ckout (3) 6 clock output 1 (unprogrammed) sut1 5 select start-up time 1 (unprogrammed) (1) sut0 4 select start-up time 0 (programmed) (1) cksel3 3 select clock source 0 (programmed) (2) cksel2 2 select clock source 0 (programmed) (2) cksel1 1 select clock source 1 (unprogrammed) (2) cksel0 0 select clock source 0 (programmed) (2) note: 1. the default value of sut1..0 results in maxi mum start-up time for the default clock source. see table 5-14 on page 54 for details. 2. the default setting of cksel3..0 results in internal rc oscillator at 8mhz. see table 5-13 on page 54 for details. 3. the ckout fuse allows the system clock to be output on portb0. see section 5.8.9 ?clock output buffer? on page 56 for details. 4. see section 5.8.11 ?system clo ck prescaler? on page 56 for details. table 5-118. device id part signature bytes address 0x000 0x001 0x002 atmega328p 0x1e 0x95 0x0f table 5-119. no. of words in a page and no. of pages in the flash device flash size page size pcword no. of pages pcpage pcmsb atmega328p 16k words (32k bytes) 64 words pc[5:0] 256 pc[13:6] 13 table 5-120. no. of words in a page and no . of pages in the eeprom device eeprom size page size pcword no. of pages pcpage eeamsb atmega328p 1k bytes 4 bytes eea[1:0] 256 eea[9:2] 9
ata6614q [datasheet] 9240h?auto?10/14 266 5.27.6 parallel programmi ng parameters, pin mapping, and commands this section describes how to parallel program and verify flash program memory, eeprom data memory, memory lock bits, and fuse bits in the atmega328p. pulses are assu med to be at least 250ns unless otherwise noted. 5.27.6.1 signal names in this section, some pins of the atmega328p are referenc ed by signal names describing thei r functionality during parallel programming, see figure 5-118 and table 5-121 . pins not described in the following table are referenced by pin names. the xa1/xa0 pins determine the action executed when the xta l1 pin is given a positive pulse. the bit coding is shown in table 5-123 . when pulsing wr or oe , the command loaded determines the action exec uted. the different co mmands are shown in table 5-124 . figure 5-118. parallel programming note: v cc ? 0.3v < av cc < v cc + 0.3v, however, av cc should always be within 4.5 to 5.5v table 5-121. pin name mapping signal name in programming mode pin name i/o function rdy/bsy pd1 o 0: device is busy programming , 1: device is ready for new command oe pd2 i output enable (active low) wr pd3 i write pulse (active low) bs1 pd4 i byte select 1 (?0? selects low byte, ?1? selects high byte) xa0 pd5 i xtal action bit 0 xa1 pd6 i xtal action bit 1 pagel pd7 i program memory and eeprom data page load bs2 pc2 i byte select 2 (?0? selects lo w byte, ?1? selects 2?nd high byte) data {pc[1:0]: pb[5:0]} i/o bi-directional data bus (output when oe is low) gnd xtal1 pc2 pd1 pd2 pd3 pd4 dat a pd5 pd6 pd7 reset vcc avcc pc[1:0]:pb[5:0] +4.5 to 5.5v +4.5 to 5.5v rdy/bsy oe wr bs1 xa0 xa1 pagel +12v bs2
267 ata6614q [datasheet] 9240h?auto?10/14 5.27.7 parallel programming 5.27.7.1 enter programming mode the following algorithm puts the device in parallel (high-voltage) programming mode: 1. set prog_enable pins listed in table 5-122 on page 267 to ?0000?, reset pin to 0v and v cc to 0v. 2. apply 4.5 to 5.5v between v cc and gnd. ensure that v cc reaches at least p?v within the next 20s. 3. wait 20 to 60s , and apply 11.5 to 12.5v to reset. 4. keep the prog_enable pins unchanged for at least 10s after the high-voltage has been applied to ensure the prog_enable signature has been latched. 5. wait at least 300s before giving any parallel programming commands. 6. exit programming mode by power the device down or by bringing reset pin to 0v. if the rise time of the v cc is unable to fulfill the requirements listed above, the following alternative algorithm can be used. 1. set prog_enable pins listed in table 5-122 on page 267 to ?0000?, reset pin to 0v and v cc to 0v. 2. apply 4.5 to 5.5v between v cc and gnd. 3. monitor v cc , and as soon as v cc reaches 0.9 - 1.1v, apply 11.5 - 12.5v to reset. 4. keep the prog_enable pins unchanged for at least 10s after the high-voltage has been applied to ensure the prog_enable signature has been latched. table 5-122. pin values used to enter programming mode pin symbol value pagel prog_enable[3] 0 xa1 prog_enable[2] 0 xa0 prog_enable[1] 0 bs1 prog_enable[0] 0 table 5-123. xa1 and xa0 coding xa1 xa0 action when xtal1 is pulsed 0 0 load flash or eeprom address (high or low address byte determined by bs1). 0 1 load data (high or low data byte for flash determined by bs1). 1 0 load command 1 1 no action, idle table 5-124. command byte bit coding command byte command executed 1000 0000 chip erase 0100 0000 write fuse bits 0010 0000 write lock bits 0001 0000 write flash 0001 0001 write eeprom 0000 1000 read signature bytes and calibration byte 0000 0100 read fuse and lock bits 0000 0010 read flash 0000 0011 read eeprom
ata6614q [datasheet] 9240h?auto?10/14 268 5. wait until v cc actually reaches 4.5 to 5.5v before giving any parallel programming commands. 6. exit programming mode by power the device down or by bringing reset pin to 0v. 5.27.7.2 considerations for efficient programming the loaded command and address are retained in the device dur ing programming. for efficient programming, the following should be considered. the command needs only be loaded once when writing or reading multiple memory locations. skip writing the data value 0xff, that is the contents of the entire eeprom (unless the eesave fuse is programmed) and flash after a chip erase. address high byte needs only be loaded before programming or reading a new 256 word window in flash or 256 byte eeprom. this consideration also applies to signature bytes reading. 5.27.7.3 chip erase the chip erase will er ase the flash and eeprom (1) memories plus lock bits. the lock bits are not reset until the program memory has been completely erased. the fuse bits are no t changed. a chip erase must be performed before the flash and/or eeprom are reprogrammed. note: 1. the eeprpom memory is preserved during chip erase if the eesave fuse is programmed. load command ?chip erase? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?1000 0000?. this is the command for chip erase. 4. give xtal1 a positive pulse. this loads the command. 5. give wr a negative pulse. this star ts the chip erase. rdy/bsy goes low. 6. wait until rdy/bsy goes high before loading a new command. 5.27.7.4 programming the flash the flash is organized in pages, see table 5-119 on page 265 . when programming the flash, th e program data is latched into a page buffer. this allows one page of program data to be programmed simultaneously. the following procedure describes how to program the entire flash memory: a. load command ?write flash? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?0001 0000?. this is the command for write flash. 4. give xtal1 a positive pulse. this loads the command. b. load address low byte 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs1 to ?0?. this selects low address. 3. set data = address low byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address low byte. c. load data low byte 1. set xa1, xa0 to ?01?. this enables data loading. 2. set data = data low byte (0x00 - 0xff). 3. give xtal1 a positive pulse. this loads the data byte. d. load data high byte 1. set bs1 to ?1?. this selects high data byte. 2. set xa1, xa0 to ?01?. this enables data loading. 3. set data = data high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the data byte.
269 ata6614q [datasheet] 9240h?auto?10/14 e. latch data 1. set bs1 to ?1?. this selects high data byte. 2. give pagel a positive pulse. this latches the data bytes. (see figure 5-120 for signal waveforms) f. repeat b through e until the entire buffer is filled or until all data within the page is loaded. while the lower bits in the address are mapped to words wi thin the page, the higher bits address the pages within the flash. this is illustrated in figure 5-119 on page 269 . note that if less than eight bits are required to address words in the page (pagesize < 256), the most significant bit(s) in the ad dress low byte are used to address the page when performing a page write. g. load address high byte 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs1 to ?1?. this selects high address. 3. set data = address high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte. h. program page 1. give wr a negative pulse. this starts programm ing of the entire page of data. rdy/bsy goes low. 2. wait until rdy/bsy goes high (see figure 5-120 for signal waveforms). i. repeat b through h until the entire flash is programmed or until all data has been programmed. j. end page programming 1. 1. set xa1, xa0 to ?10?. this enables command loading. 2. set data to ?0000 0000?. this is the command for no operation. 3. give xtal1 a positive pulse. this loads the co mmand, and the internal write signals are reset. figure 5-119. addressing the flash which is organized in pages (1) note: 1. pcpage and pcword are listed in table 5-119 on page 265 . pagemsb pcmsb program counter word address within page page address within the flash pcword pcpage 02 01 00 pageend pcword [pagemsb : 0] page program memory instructions word page
ata6614q [datasheet] 9240h?auto?10/14 270 figure 5-120. programming the flash waveforms (1) note: 1. ?xx? is don?t care. the letters re fer to the programming description above. 5.27.7.5 programming the eeprom the eeprom is organized in pages, see table 5-120 on page 265 . when programming the eeprom, the program data is latched into a page buffer. this allows one page of data to be programmed simultaneously. the programming algorithm for the eeprom data memory is as follows (refer to section 5.27.7.4 ?programming the flash? on page 268 for details on command, address and data loading): 1. a: load command ?0001 0001?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. c: load data (0x00 - 0xff). 5. e: latch data (give pagel a positive pulse). k: repeat 3 through 5 until the entire buffer is filled. l: program eeprom page 1. set bs1 to ?0?. 2. give wr a negative pulse. this starts pr ogramming of the eeprom page. rdy/bsy goes low. 3. wait until to rdy/bsy goes high before programming the next page (see figure 5-121 on page 271 for signal waveforms). 0x10 addr. low ab data xa1 xa0 bs1 xtal1 wr pagel rdy/bsy oe reset +12v data low data high cd addr. low b data low data high cd f xx e xx e xx i addr. high g addr.ext.h h bs2
271 ata6614q [datasheet] 9240h?auto?10/14 figure 5-121. pr ogramming the eepr om waveforms 5.27.7.6 reading the flash the algorithm for reading the flash memory is as follows (refer to section 5.27.7.4 ?programming the flash? on page 268 for details on command and address loading): 1. a: load command ?0000 0010?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the flash word low byte can now be read at data. 5. set bs1 to ?1?. the flash word high byte can now be read at data. 6. set oe to ?1?. 5.27.7.7 reading the eeprom the algorithm for reading the eeprom memory is as follows (refer to section 5.27.7.4 ?programming the flash? on page 268 for details on command and address loading): 1. a: load command ?0000 0011?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the eeprom data byte can now be read at data. 5. set oe to ?1?. 5.27.7.8 programming the fuse low bits the algorithm for programming the fuse low bits is as follows (refer to section 5.27.7.4 ?programming the flash? on page 268 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. give wr a negative pulse and wait for rdy/bsy to go high. 0x11 ag data xa1 xa0 bs1 bs2 xtal1 wr pagel rdy/bsy oe reset +12v bc addr. low addr. low b data xx ce k xx data el addr. high
ata6614q [datasheet] 9240h?auto?10/14 272 5.27.7.9 programming the fuse high bits the algorithm for programming the fuse high bits is as follows (refer to section 5.27.7.4 ?programming the flash? on page 268 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs1 to ?1? and bs2 to ?0?. this selects high data byte. 4. give wr a negative pulse and wait for rdy/bsy to go high. 5. set bs1 to ?0?. this selects low data byte. 5.27.7.10 programming the extended fuse bits the algorithm for programming the extended fuse bits is as follows (refer to section 5.27.7.4 ?programming the flash? on page 268 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs1 to ?0? and bs2 to ?1?. this selects extended data byte. 4. give wr a negative pulse and wait for rdy/bsy to go high. 5. set bs2 to ?0?. this selects low data byte. figure 5-122. pr ogramming the fuses waveforms 5.27.7.11 programming the lock bits the algorithm for programming the lock bits is as follows (refer to section 5.27.7.4 ?programmi ng the flash? on page 268 for details on command and data loading): 1. a: load command ?0010 0000?. 2. c: load data low byte. bit n = ?0? programs the lock bit. if lb mode 3 is programmed (lb1 and lb2 is pro- grammed), it is not possible to program the boot lock bits by any external programming mode. 3. give wr a negative pulse and wait for rdy/bsy to go high. the lock bits can only be cleared by executing chip erase. 0x40 ac data xa1 xa0 bs1 bs2 xtal1 wr pagel rdy/bsy oe reset +12v 0x40 0x40 data a data xx c write fuse low byte write fuse high byte write extended fuse byte xx data a xx c
273 ata6614q [datasheet] 9240h?auto?10/14 5.27.7.12 reading the fuse and lock bits the algorithm for reading the fuse and lock bits is as follows (refer to section 5.27.7.4 ?programming the flash? on page 268 for details on command loading): 1. a: load command ?0000 0100?. 2. set oe to ?0?, bs2 to ?0? and bs1 to ?0?. the status of the fuse low bits can now be read at data (?0? means programmed). 3. set oe to ?0?, bs2 to ?1? and bs1 to ?1?. the status of t he fuse high bits can now be read at data (?0? means programmed). 4. set oe to ?0?, bs2 to ?1?, and bs1 to ?0?. the status of the extended fuse bits can now be read at data (?0? means programmed). 5. set oe to ?0?, bs2 to ?0? and bs1 to ?1?. the status of the lock bits can now be read at data (?0? means programmed). 6. set oe to ?1?. figure 5-123. mapping between bs1, bs2 an d the fuse and lock bits during read 5.27.7.13 reading the signature bytes the algorithm for reading the signature bytes is as follows (refer to section 5.27.7.4 ?programming the flash? on page 268 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte (0x00 - 0x02). 3. set oe to ?0?, and bs1 to ?0?. the selected signature byte can now be read at data. 4. set oe to ?1?. 5.27.7.14 reading the calibration byte the algorithm for reading the calibration byte is as follows (refer to section 5.27.7.4 ?programming the flash? on page 268 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte, 0x00. 3. set oe to ?0?, and bs1 to ?1?. the calibration byte can now be read at data. 4. set oe to ?1?. 5.27.7.15 parallel programming characteristics for characteristics of the parallel programming, see section 5.28.9 ?parallel programming characteristics? on page 285 . extended fuse byte 0 1 fuse low byte bs2 fuse high byte 0 1 lock bits bs2 bs1 data 0 1
ata6614q [datasheet] 9240h?auto?10/14 274 5.27.8 serial downloading both the flash and eeprom memory arrays can be programmed usi ng the serial spi bus while reset is pulled to gnd. the serial interface consists of pins sck, mosi (input) and miso (output). after reset is set low, the programming enable instruction needs to be executed first before pr ogram/erase operations can be executed. note, in table 5-125 on page 274 , the pin mapping for spi programming is listed. not all parts use the spi pins dedicated for the internal spi interface. figure 5-124. serial programming and verify (1) notes: 1. if the device is clocked by the in ternal oscillator, it is no need to connect a clock source to the xtal1 pin. 2. v cc - 0.3v < av cc < v cc + 0.3v, however, av cc should always be within 2.7 - 5.5v when programming the eeprom, an auto-erase cycle is built into the self-timed programming operation (in the serial mode only) and there is no need to first execute the chip erase inst ruction. the chip erase operat ion turns the content of every memory location in bo th the program and eepr om arrays into 0xff. depending on cksel fuses, a vali d clock must be present. the minimum low an d high periods for the serial clock (sck) input are defined as follows: low: > 2 cpu clock cycles for f ck < 12mhz, 3 cpu clock cycles for f ck 12mhz high: > 2 cpu clock cycles for f ck < 12mhz, 3 cpu clock cycles for f ck 12mhz 5.27.8.1 serial programming pin mapping gnd xtal1 reset vcc avcc +1.8v to 5.5v +1.8v to 5.5v (2) mosi miso sck table 5-125. pin mapping serial programming symbol pins i/o description mosi pb3 i serial data in miso pb4 o serial data out sck pb5 i serial clock
275 ata6614q [datasheet] 9240h?auto?10/14 5.27.8.2 serial pr ogramming algorithm when writing serial data to the atmega328p, data is clocked on the rising edge of sck. when reading data from the at mega328p, data is clocked on the falling edge of sck. see figure 5-126 for timing details. to program and verify the atmega328p in the serial programming mode, the following sequence is recommended (see serial programming instruction set in table 5-127 on page 276 ): 1. power-up sequence: apply power between v cc and gnd while reset and sck are set to ?0?. in so me systems, the programmer can not guarantee that sck is held low dur ing power-up. in this case, reset must be given a positive pulse of at least two cpu clock cycles durati on after sck has been set to ?0?. 2. wait for at least 20ms and enable serial programming by sending the programming enable serial instruction to pin mosi. 3. the serial programming instructions will not work if t he communication is out of syn chronization. when in sync. the second byte (0x53), will echo back when issuing the thir d byte of the programming enable instruction. whether the echo is correct or not, all four byte s of the instruction must be transmitt ed. if the 0x53 did not echo back, give reset a positive pulse and issue a new programming enable command. 4. the flash is programmed one page at a time. the memory page is loaded one byte at a time by supplying the 6 lsb of the address and data together wi th the load program memory page instruction. to ensure correct loading of the page, the data low byte must be loaded before dat a high byte is applied for a given address. the program memory page is stored by loading the write program memo ry page instruction with the 7 msb of the address. if polling (rdy/bsy ) is not used, the user must wait at least t wd_flash before issuing the next page (see table 5- 126 ). accessing the serial programming interface before the flash write operation completes can result in incorrect programming. 5. a : the eeprom array is programmed one byte at a ti me by supplying the address and data together with the appropriate write instruction. an eeprom memory location is first automatically eras ed before new data is writ- ten. if polling (rdy/bsy ) is not used, the user must wait at least t wd_eeprom before issuing th e next byte (see table 5-126 ). in a chip erased device, no 0xffs in the data file(s) need to be programmed. b : the eeprom array is programmed one pa ge at a time. the memory page is loaded one byte at a time by sup- plying the 6 lsb of the address and data together wit h the load eeprom memory page instruction. the eeprom memory page is stored by loading the write eepr om memory page instruct ion with the 7 msb of the address. when using eeprom page access only byte loca tions loaded with the load eeprom memory page instruction is altered. the remaining loca tions remain unchanged. if polling (rdy/bsy ) is not used, the used must wait at least t wd_eeprom before issuing the next byte (see table 5-126 ). in a chip erased device, no 0xff in the data file(s) need to be programmed. 6. any memory location can be verified by using the read instruction which returns the content at the selected address at serial output miso. 7. at the end of the programming session, reset can be set high to commence normal operation. 8. power-off sequence (if needed): set reset to ?1?. turn v cc power off. table 5-126. typical wait de lay before writing the next flash or eeprom location symbol minimum wait delay t wd_flash 4.5ms t wd_eeprom 3.6ms t wd_erase 9.0ms
ata6614q [datasheet] 9240h?auto?10/14 276 5.27.8.3 serial progra mming instruction set table 5-127 on page 276 and figure 5-125 on page 277 describes the instruction set. if the lsb in rdy/bsy data byte out is ?1?, a programming oper ation is still pending. wait until this bit returns ?0? before th e next instruction is carried out. within the same page, the low data byte must be loaded prior to the high data byte. after data is loaded to the page buffer, program the eeprom page, see figure 5-125 on page 277 . table 5-127. serial programming instruction set (hexadecimal values) instruction/operation instruction format byte 1 byte 2 byte 3 byte4 programming enable $ac $53 $00 $00 chip erase (program memory/eeprom) $ac $80 $00 $00 poll rdy/bsy $f0 $00 $00 data byte out load instructions load extended address byte (1) $4d $00 extended adr $00 load program memory page, high byte $48 $00 adr lsb high data byte in load program memory page, low byte $40 $00 adr lsb low data byte in load eeprom memory page (page access) $c1 $00 0000 000aa data byte in read instructions read program memory, high byte $28 adr msb adr lsb high data byte out read program memory, low byte $20 adr msb adr lsb low data byte out read eeprom memory $a0 0000 00aa aaaa aaaa data byte out read lock bits $58 $00 $00 data byte out read signature byte $30 $00 0000 000aa data byte out read fuse bits $50 $00 $00 data byte out read fuse high bits $58 $08 $00 data byte out read extended fuse bits $50 $08 $00 data byte out read calibration byte $38 $00 $00 data byte out write instructions (6) write program memory page $4c adr msb adr lsb $00 write eeprom memory $c0 0000 00aa aaaa aaaa data byte in write eeprom memory page (page access) $c2 0000 00aa aaaa aa00 $00 write lock bits $ac $e0 $00 data byte in write fuse bits $ac $a0 $00 data byte in write fuse high bits $ac $a8 $00 data byte in write extended fuse bits $ac $a4 $00 data byte in notes: 1. not all instructions are applicable for all parts. 2. a = address. 3. bits are programmed ?0?, unprogrammed ?1?. 4. to ensure future compatibility, unused fuses and lock bits should be unprogrammed (?1?). 5. refer to the corresponding section for fuse and lock bits, calibration and signature bytes and page size. 6. instructions accessing program memory use a word addr ess. this address may be random within the page range. 7. see http://www.atmel.com/avr for application notes regarding programming and programmers.
277 ata6614q [datasheet] 9240h?auto?10/14 figure 5-125. serial progra mming instruction example 5.27.8.4 spi serial programming characteristics figure 5-126. serial programming waveforms for characteristics of the spi module see section 5.28.6 ?spi timing ch aracteristics? on page 281 . byte 1 byte 2 byte 3 byte 4 page 0 page 1 page 2 adr lbs adr mbs bit 15 b 0 bit 15 b 0 byte 1 byte 2 byte 3 byte 4 adr lbs adr mbs page n-1 program memory / eeprom memory serial programming instruction page buffer page number page offset load program memory page (high/low byte)/ load eeprom memory page (page access) write program memory page / write eeprom memory page serial data input (mosi) serial data output (miso) serial clock input (sck) sample msb lsb msb lsb
ata6614q [datasheet] 9240h?auto?10/14 278 5.28 electrical characteristics all dc/ac characteristics contained in this data sheet are based on characterization of atmega328p avr ? microcontroller manufactured in an automotive process technology. 5.28.1 dc characteristics t case = ?40c to 125c, v cc = 2.7v to 5.5v (unless otherwise noted) parameter condition symbol min. typ. max. unit input low voltage, except xtal1 and reset pin v cc = 2.7v - 5.5v v il ?0.5 0.3v cc (1) v input high voltage, except xtal1 and reset pins v cc = 2.7v - 5.5v v ih 0.6v cc (2) v cc + 0.5 v input low voltage, xtal1 pin v cc = 2.7v - 5.5v v il1 ?0.5 0.1v cc (1) v input high voltage, xtal1 pin v cc = 2.7v - 5.5v v ih1 0.7v cc (2) v cc + 0.5 v input low voltage, reset pin v cc = 2.7v - 5.5v v il2 ?0.5 0.1v cc (1) v input high voltage, reset pin v cc = 2.7v - 5.5v v ih2 0.9v cc (2) v cc + 0.5 v output low voltage (3) i ol = 20ma, v cc = 5v i ol = 5ma, v cc = 3v v ol 0.8 0.5 v output high voltage (4) i oh = ?20ma, v cc = 5v i oh = ?10ma, v cc = 3v v oh 4.1 2.3 v input leakage current i/o pin v cc = 5.5v, pin low (absolute value) i il 1 a input leakage current i/o pin v cc = 5.5v, pin high (absolute value) i ih 1 a reset pull-up resistor r rst 30 60 k i/o pin pull-up resistor r pu 20 50 k analog comparator input offset voltage 0.4v < v in < v cc ? 0.5 (absolute value) v acio 10 40 mv analog comparator input leakage current v cc = 5v v in = v cc /2 i aclk ?50 50 na notes: 1. ?max? means the highest value where the pin is guaranteed to be read as low 2. ?min? means the lowest value where the pin is guaranteed to be read as high 3. although each i/o port can sink more than the test conditions (20ma at v cc = 5v, 10 ma at v cc = 3v) under steady state conditions (non-transient), the following must be observed: atmega328p: 1] the sum of all i ol , for ports c0 - c5, should not exceed 100ma. 2] the sum of all i ol , for ports b0 - b5, d5 - d7, xtal1, xtal2 should not exceed 100ma. 3] the sum of all i ol , for ports d0 - d4, should not exceed 100ma. if i ol exceeds the test condition, v ol may exceed the related specification. pins are not guaranteed to sink current greater than the listed test condition. 4. although each i/o port can source more than the test conditions (20ma at v cc = 5v, 10ma at v cc = 3v) under steady state conditions (non-transient), the following must be observed: atmega328p: 1] the sum of all i oh , for ports c0 - c5, d0- d4, should not exceed 150ma. 2] the sum of all i oh , for ports b0 - b5, d5 - d7, xtal1, xtal2 should not exceed 150ma. if ii oh exceeds the test condition, v oh may exceed the related specification. pi ns are not guaranteed to source current greater than the listed test condition.
279 ata6614q [datasheet] 9240h?auto?10/14 5.28.3 speed grades figure 5-127. maximum frequency 5.28.4 clock characteristics 5.28.4.1 calibrate d internal rc oscillator accuracy 5.28.2 dc characteristics t case = ?40c to 125c, v cc = 2.7v to 5.5v (unless otherwise noted) symbol parameter condition min. typ. (2) max. unit i cc power supply current (1) active 4mhz, v cc = 3v 1.5 2.4 ma active 8mhz, v cc = 5v 5.2 10 ma active 16mhz, v cc = 5v 9.2 14 ma idle 4mhz, v cc = 3v 0.25 0.6 ma idle 8mhz, v cc = 5v 1.0 1.6 ma idle 16mhz, v cc = 5v 1.9 2.8 ma power-down mode (3) wdt enabled, v cc = 3v 44 a wdt enabled, v cc = 5v 66 a wdt disabled, v cc = 3v 40 a wdt disabled, v cc = 5v 60 a notes: 1. values with ?minimizing power consumption? enabled (0xff). 2. typical values at 25c. 3. the current consumption values include input leakage current. safe operating area 2.7v 8mhz 16mhz 5.5v 4.5v table 5-128. calibration accura cy of internal rc oscillator frequency v cc temperature calibration accuracy factory calibration 8.0mhz 3v 25c 2% 2.7v - 5.5v ?40c - 125c 14%
ata6614q [datasheet] 9240h?auto?10/14 280 5.28.4.2 watchdog oscillator accuracy 5.28.4.3 external clock drive waveforms figure 5-128. external clock drive waveforms 5.28.4.4 external clock drive 5.28.5 system and reset characteristics table 5-129. accuracy of watchdog oscillator parameter condition symbol min typ max unit watchdog oscillator frequency v cc = 2.7 - 5.5v fwdt 76 128 180 khz t chcx v ih1 v il1 t chcx t clch t chcl t clcx t clcl table 5-130. external clock drive parameter symbol v cc = 2.7-5.5v v cc = 4.5-5.5v unit min. max. min. max. oscillator frequency 1/t clcl 0 8 0 20 mhz high time t chcx 50 25 ns low time t clcx 50 25 ns rise time t clch 1.6 0.5 ns fall time t chcl 1.6 0.5 ns change in period from one clock cycle to the next t clcl 2 2 % note: all dc/ac characteristics contained in this datas heet are based on characterization of atmega328p avr ? microcon- troller manufactured in an automotive process technology. table 5-131. reset, brown-out and internal voltage characteristics parameter condition symbol min typ max unit brown-out detector hysteresis v hyst 80 mv bandgap reference voltage v cc =5v v bg 1.0 1.1 1.2 v
281 ata6614q [datasheet] 9240h?auto?10/14 5.28.6 spi timing characteristics see figure 5-129 and figure 5-130 for details. table 5-132. b odlevel fuse coding (1) bodlevel 2:0 fuses min v bot typ v bot max v bot unit 111 bod disabled 110 reserved v 101 2.5 2.7 2.9 100 4.0 4.3 4.6 011 reserved 010 001 000 notes: 1. v bot may be below nominal minimum operating voltage for some devices. for devices where this is the case, the device is tested down to v cc = v bot during the production test. this guarantees that a brown-out reset will occur before v cc drops to a voltage where correct operation of the microcont roller is no longer guaranteed. the test is performed using bodlevel = 100 and bodlevel = 101 for atmega328p. table 5-133. spi timing parameters no. description mode min typ max unit 1 sck period master see table 5-68 ns 2 sck high/low master 50% duty cycle 3 rise/fall time master 3.6 4 setup master 10 5 hold master 10 6 out to sck master 0.5 t sck 7 sck to out master 10 8 sck to out high master 10 9 ss low to out slave 15 10 sck period slave 4 t ck 11 sck high/low (1) slave 2 t ck 12 rise/fall time slave 1600 13 setup slave 10 14 hold slave t ck 15 sck to out slave 15 16 sck to ss high slave 20 17 ss high to tri-state slave 10 18 ss low to sck slave 20 note: 1. in spi programming mode the minimum sck high/low period is: - 2 t clcl for f ck < 12mhz - 3 t clcl for f ck > 12mhz all ac/ac characteristics contained in this datasheet are based on characterization of atmega328p avr ? microcontroller manufac- tured in an automotive process technology.
ata6614q [datasheet] 9240h?auto?10/14 282 figure 5-129. spi interface timi ng requirements (master mode) figure 5-130. spi interface timing requirements (slave mode) 6 msb ss sck (cpol = 0) sck (cpol = 1) miso (data input) mosi (data output) msb lsb lsb ... ... 45 8 7 1 2 2 3 9 msb ss sck (cpol = 0) sck (cpol = 1) mosi (data input) miso (data output) msb lsb x lsb ... ... 13 14 17 15 10 16 11 11 12
283 ata6614q [datasheet] 9240h?auto?10/14 5.28.7 2-wire serial interface characteristics table 5-134 describes the requirements for devices connected to the 2-wire serial bus. the atmega328p 2-wire serial interface meets or exceeds these r equirements under the noted conditions. timing symbols refer to figure 5-131 . table 5-134. 2-wire serial bus requirements parameter condition symbol min max unit input low-voltage v il -0.5 0.3 v cc v input high-voltage v ih 0.7 v cc v cc + 0.5 v hysteresis of schmitt trigger inputs v hys (1) 0.05 v cc (2) ? v output low-voltage 3 ma sink current v ol (1) 0 0.4 v rise time for both sda and scl t r (1) 20 + 0.1c b (2)(3) 300 ns output fall time from v ihmin to v ilmax 10pf < c b < 400pf (3) t of (1) 20 + 0.1c b (2)(3) 250 ns spikes suppressed by input filter t sp (1) 0 50 (2) ns input current each i/o pin 0.1v cc < v i < 0.9v cc i i -10 10 a capacitance for each i/o pin c i (1) ? 10 pf scl clock frequency f ck (4) > max(16f scl , 250khz) (5) f scl 0 400 khz value of pull-up resistor f scl 100khz r p f scl > 100khz hold time (repeated) start condition f scl 100khz t hd;sta 4.0 ? s f scl > 100khz 0.6 ? s low period of the scl clock f scl 100khz t low 4.7 ? s f scl > 100khz 1.3 ? s high period of the scl clock f scl 100khz t high 4.0 ? s f scl > 100khz 0.6 ? s set-up time for a repeated start condition f scl 100khz t su;sta 4.7 ? s f scl > 100khz 0.6 ? s data hold time f scl 100khz t hd;dat 0 3.45 s f scl > 100khz 0 0.9 s data setup time f scl 100khz t su;dat 250 ? ns f scl > 100khz 100 ? ns setup time for stop condition f scl 100khz t su;sto 4.0 ? s f scl > 100khz 0.6 ? s bus free time between a stop and start condition f scl 100khz t buf 4.7 ? s f scl > 100khz 1.3 ? s notes: 1. in atmega328p, this parameter is characterized and not 100% tested. 2. required only for f scl > 10 khz. 3. c b = capacitance of one bus line in pf. 4. f ck = cpu clock frequency 5. this requirement applies to all atmega328p 2-wire serial interface operation. other de vices connected to the 2-wire serial bus need only obey the general f scl requirement. v cc 0,4v ? 3ma --------------------------- - 1000ns c b ---------------- - v cc 0,4v ? 3ma --------------------------- - 300ns c b ------------- -
ata6614q [datasheet] 9240h?auto?10/14 284 figure 5-131. 2-wire serial bus timing 5.28.8 adc characteristics t of t su,sta t hd,sta t hd,sta t buf t hd,dat t su,dat t high t low t low scl sda t r table 5-135. adc characteristics parameter condition symbol min typ max unit resolution ?40c +125c / 2.70 - 5.50v adc clock = 200khz 10 bits absolute accuracy v cc = 4.0v, v ref = 4.0v tue 2.2 3.5 lsb integral non linearity v cc = 4.0v, v ref = 4.0v inl 0.6 1.5 lsb differential non linearity v cc = 4.0v, v ref = 4.0v dnl 0.3 0.7 lsb gain error v cc = 4.0v, v ref = 4.0v ?3.5 3.5 lsb offset error v cc = 4.0v, v ref = 4.0v ?3.5 3.5 lsb clock frequency 50 200 khz analog supply voltage av cc v cc ? 0.3 v cc +0.3 v reference voltage v ref 1.0 av cc v input voltage v in gnd v ref v internal voltage reference v cc = 5v v int 1.0 1.1 1.2 v reference input resistance r ref 22.4 32 41.6 k analog input resistance r ain 100 m
285 ata6614q [datasheet] 9240h?auto?10/14 5.28.9 parallel programming characteristics table 5-136. parallel progra mming characteristics, v cc = 5v 10% parameter symbol min typ max unit programming enable voltage v pp 11.5 12.5 v programming enable current i pp 250 a data and control valid before xtal1 high t dvxh 67 ns xtal1 low to xtal1 high t xlxh 200 ns xtal1 pulse width high t xhxl 150 ns data and control hold after xtal1 low t xldx 67 ns xtal1 low to wr low t xlwl 0 ns xtal1 low to pagel high t xlph 0 ns pagel low to xtal1 high t plxh 150 ns bs1 valid before pagel high t bvph 67 ns pagel pulse width high t phpl 150 ns bs1 hold after pagel low t plbx 67 ns bs2/1 hold after wr low t wlbx 67 ns pagel low to wr low t plwl 67 ns bs1 valid to wr low t bvwl 67 ns wr pulse width low t wlwh 150 ns wr low to rdy/bsy low t wlrl 0 1 s wr low to rdy/bsy high (1) t wlrh 3.7 4.5 ms wr low to rdy/bsy high for chip erase (2) t wlrh_ce 7.5 9 ms xtal1 low to oe low t xlol 0 ns bs1 valid to data valid t bvdv 0 250 ns oe low to data valid t oldv 250 ns oe high to data tri-stated t ohdz 250 ns notes: 1. t wlrh is valid for the write flash, write eeprom, write fuse bits and write lock bits commands. 2. t wlrh_ce is valid for the chip erase command.
ata6614q [datasheet] 9240h?auto?10/14 286 figure 5-132. parallel programmi ng timing, including some general timing requirements figure 5-133. parallel programming timing, loading sequence with timing requirements (1) note: 1. the timing requirements shown in figure 5-132 (i.e., t dvxh , t xhxl , and t xldx ) also apply to loading operation. figure 5-134. parallel programming timing, reading sequence (within the same page) with timing requirements (1) note: 1. the timing requirements shown in figure 5-132 (i.e., t dvxh , t xhxl , and t xldx ) also apply to reading operation. xtal1 pagel wr data and control (data, xa0/1, bs1, bs2) t xhxl t dvxh t bvph t xlwl t xldx t phpl t plbx t plwl t bvwl t wlbx t wlwh t wlrl t wlrh rdy/bsy xtal1 bs1 pagel data xa0 xa1 t xlxh t plxh t xlph load address (low byte) load data (low byte) load data (high byte) load address (low byte) load data addr0 (low byte) addr1 (low byte) data (low byte) data (high byte) xtal1 bs1 oe data xa0 xa1 t bvdv t xlol t oldv t ohdz load address (low byte) read data (low byte) read data (high byte) load address (low byte) addr0 (low byte) addr1 (low byte) data (low byte) data (high byte)
287 ata6614q [datasheet] 9240h?auto?10/14 5.29 typical characteristics the data contained in this section are characterized values of actual automotive silicon. unless otherwise specified, the data contained in this chapter are for ?40 to 125c. the following charts show typical behavior. these figures ar e not tested during manufactur ing. all current consumption measurements are performed with all i/o pins configured as inputs and with internal pull-ups enabled. a square wave generator with rail-to-rail output is used as clock source. all active- and idle current consumption measurements are done with all bits in the prr register set and thus, the corresponding i/o modules are turned off. also the analog co mparator is disabled during th ese measurements. the ?supply current of io modules? shows the additi onal current consumption compared to i cc active and i cc idle for every i/o module controlled by the power reduction register. see section 5.9.9 ?power reduction register? on page 60 for details. the power consumption in power-down mode is independent of clock selection. the current consumption is a function of several factors such as: operating voltage, operating fr equency, loading of i/o pins, switching rate of i/o pins, code exec uted and ambient temperature. the dominat ing factors are operating voltage and frequency. the current drawn from capacitive loaded pins may be estimated (for one pin) as c l *v cc *f where c l = load capacitance, v cc = operating voltage and f = average switching frequency of i/o pin. the parts are characterized at frequencies higher than test limits. parts are no t guaranteed to function properly at frequencies higher than the ordering code indicates. the difference between current consumption in power-down mode with watchdog timer enabled and power-down mode with watchdog timer disabled represents the differential current drawn by the watchdog timer. 5.29.1 atmega328p typical characteristics 5.29.1.1 active supply current figure 5-135. active supply current versus frequency frequency (mhz) 0 2 4 6 8 10 12 14 16 18 20 i cc (ma) 14 16 12 10 8 6 4 2 0 5.5 5.0 4.5 3.6 3.3 3.0 2.7
ata6614q [datasheet] 9240h?auto?10/14 288 figure 5-136. idle supply current versus frequency 5.29.1.2 power-down supply current figure 5-137. power-down supply current versus v cc (watchdog timer disabled) figure 5-138. power-down supply current versus v cc (watchdog timer enabled) frequency (mhz) 0 2 4 6 8 101214161820 i cc (ma) 3.5 4 3 2.5 2 1.5 1 0.5 0 5.5 5.0 4.5 3.6 3.3 3.0 2.7 i cc (a) 20 25 15 10 5 0 v cc (v) 2 2.5 3 3.5 4 4.5 5 5.5 125 85 25 -45 i cc (a) 30 35 25 20 15 10 5 0 v cc (v) 2 2.5 3 3.5 4 4.5 5 5.5 125 85 25 -45
289 ata6614q [datasheet] 9240h?auto?10/14 5.29.1.3 pin pull-up figure 5-139. i/o pin pull-up resist or current versus input voltage (v cc = 5v) figure 5-140. reset pull-up resistor current versus reset pin voltage (v cc = 5v) 5.29.1.4 pin driver strength figure 5-141. i/o pin output voltage versus sink current (v cc = 3v) v op (v) 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 i op (a) 140 160 120 100 80 60 40 20 0 125 85 25 -45 v reset (v) 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 i reset (a) 100 120 80 60 40 20 40 125 85 25 -45 i ol (ma) 0 2 4 6 8 10 12 14 16 18 20 v ol (v) 1 1.2 0.8 0.6 0.4 0.2 0 125 85 25 -45
ata6614q [datasheet] 9240h?auto?10/14 290 figure 5-142. i/o pin output voltage versus sink current (v cc = 5v) figure 5-143. i/o pin output vo ltage versus source current (v cc = 3v) figure 5-144. i/o pin output vo ltage versus source current (v cc = 5v) i ol (ma) 0 2 4 6 8 101214161820 v ol (v) 0.6 0.7 0.5 0.4 0.3 0.2 0.1 0 125 85 25 -45 i oh (ma) 0 2 4 6 8 10 12 14 16 18 20 v oh (v) 3 3.5 2.5 2 1.5 1 0.5 0 125 85 25 -45 i oh (ma) 0 2 4 6 8 10 12 14 16 18 20 v oh (v) 4.8 4.9 5.0 5.1 4.7 4.6 4.5 4.4 4.3 4.2 125 85 25 -45
291 ata6614q [datasheet] 9240h?auto?10/14 5.29.1.5 pin threshold and hysteresis figure 5-145. i/o pin input threshold voltage versus v cc (v ih , i/o pin read as ?1?) figure 5-146. i/o pin input threshold voltage versus v cc (v il , i/o pin read as ?0?) figure 5-147. reset input threshold voltage versus v cc (v ih , i/o pin read as ?1?) v cc (v) 2 2.5 3 3.5 4 4.5 5 5.5 threshold (v) 3 3.5 2.5 2 1.5 1 0.5 0 125 85 25 -45 v cc (v) 2 2.5 3 3.5 4 4.5 5 5.5 threshold (v) 2.5 2 1.5 1 0.5 0 125 85 25 -45
ata6614q [datasheet] 9240h?auto?10/14 292 figure 5-148. reset input threshold voltage versus v cc (v il , i/o pin read as ?0?) 5.29.1.6 bod threshold figure 5-149. bod thresholds versus temperature (bodlevel is 2.7v) figure 5-150. bod thresholds versus temperature (bodlevel is 4.3v) v cc (v) 2 2.5 3 3.5 4 4.5 5 5.5 threshold (v) 2.5 2 1.5 1 0.5 0 125 85 25 -45 temperature (c) -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110 120 130 140 threshold (v) 2.9 3.0 2.8 2.7 2.6 2.5 2.4 1 0 temperature (c) -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 110 120 130 140 threshold (v) 4.5 4.6 4.4 4.3 4.2 4.1 4 1 0
293 ata6614q [datasheet] 9240h?auto?10/14 5.29.1.7 internal oscillator speed figure 5-151. watchdog oscillator frequency versus temperature figure 5-152. calibrated 8mhz rc oscillator frequency versus temperature figure 5-153. calibrated 8mhz rc oscillator frequency versus osccal value temperature (c) -40-30-20-10 0 10 2030405060708090100110120 f rc (khz) 150 160 140 130 120 110 100 90 80 5.5 5.0 4.5 3.3 3.0 2.7 temperature (c) -45-35-25-15 -5 5 15253545 5565 758595105115125 f rc (mhz) 8.3 8.4 8.2 8.1 8.0 7.9 7.8 7.7 7.6 5.5 5.0 4.5 3.3 3.0 2.7 osccal (x1) 0 50 100 150 200 250 f rc (mhz) 10 8 6 16 14 12 4 2 0 125 85 25 -45
ata6614q [datasheet] 9240h?auto?10/14 294 5.30 register summary address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page (0xff) reserved ? ? ? ? ? ? ? ? (0xfe) reserved ? ? ? ? ? ? ? ? (0xfd) reserved ? ? ? ? ? ? ? ? (0xfc) reserved ? ? ? ? ? ? ? ? (0xfb) reserved ? ? ? ? ? ? ? ? (0xfa) reserved ? ? ? ? ? ? ? ? (0xf9) reserved ? ? ? ? ? ? ? ? (0xf8) reserved ? ? ? ? ? ? ? ? (0xf7) reserved ? ? ? ? ? ? ? ? (0xf6) reserved ? ? ? ? ? ? ? ? (0xf5) reserved ? ? ? ? ? ? ? ? (0xf4) reserved ? ? ? ? ? ? ? ? (0xf3) reserved ? ? ? ? ? ? ? ? (0xf2) reserved ? ? ? ? ? ? ? ? (0xf1) reserved ? ? ? ? ? ? ? ? (0xf0) reserved ? ? ? ? ? ? ? ? (0xef) reserved ? ? ? ? ? ? ? ? (0xee) reserved ? ? ? ? ? ? ? ? (0xed) reserved ? ? ? ? ? ? ? ? (0xec) reserved ? ? ? ? ? ? ? ? (0xeb) reserved ? ? ? ? ? ? ? ? (0xea) reserved ? ? ? ? ? ? ? ? (0xe9) reserved ? ? ? ? ? ? ? ? (0xe8) reserved ? ? ? ? ? ? ? ? (0xe7) reserved ? ? ? ? ? ? ? ? (0xe6) reserved ? ? ? ? ? ? ? ? (0xe5) reserved ? ? ? ? ? ? ? ? (0xe4) reserved ? ? ? ? ? ? ? ? (0xe3) reserved ? ? ? ? ? ? ? ? (0xe2) reserved ? ? ? ? ? ? ? ? (0xe1) reserved ? ? ? ? ? ? ? ? (0xe0) reserved ? ? ? ? ? ? ? ? (0xdf) reserved ? ? ? ? ? ? ? ? (0xde) reserved ? ? ? ? ? ? ? ? (0xdd) reserved ? ? ? ? ? ? ? ? (0xdc) reserved ? ? ? ? ? ? ? ? (0xdb) reserved ? ? ? ? ? ? ? ? notes: 1. for compatibility with future devices, reserved bits sh ould be written to zero if accessed. reserved i/o memory addresses should never be written. 2. i/o registers within the address range 0x00 - 0x1f are direct ly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be c hecked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avr ? s, the cbi and sbi instructions will only operate on t he specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions wo rk with registers 0x00 to 0x1f only. 4. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega328p is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used.
295 ata6614q [datasheet] 9240h?auto?10/14 (0xda) reserved ? ? ? ? ? ? ? ? (0xd9) reserved ? ? ? ? ? ? ? ? (0xd8) reserved ? ? ? ? ? ? ? ? (0xd7) reserved ? ? ? ? ? ? ? ? (0xd6) reserved ? ? ? ? ? ? ? ? (0xd5) reserved ? ? ? ? ? ? ? ? (0xd4) reserved ? ? ? ? ? ? ? ? (0xd3) reserved ? ? ? ? ? ? ? ? (0xd2) reserved ? ? ? ? ? ? ? ? (0xd1) reserved ? ? ? ? ? ? ? ? (0xd0) reserved ? ? ? ? ? ? ? ? (0xcf) reserved ? ? ? ? ? ? ? ? (0xce) reserved ? ? ? ? ? ? ? ? (0xcd) reserved ? ? ? ? ? ? ? ? (0xcc) reserved ? ? ? ? ? ? ? ? (0xcb) reserved ? ? ? ? ? ? ? ? (0xca) reserved ? ? ? ? ? ? ? ? (0xc9) reserved ? ? ? ? ? ? ? ? (0xc8) reserved ? ? ? ? ? ? ? ? (0xc7) reserved ? ? ? ? ? ? ? ? (0xc6) udr0 usart i/o data register 180 (0xc5) ubrr0h ? ? ? ? usart baud rate register high 184 (0xc4) ubrr0l usart baud rate register low 184 (0xc3) reserved ? ? ? ? ? ? ? ? (0xc2) ucsr0c umsel01 umsel00 upm01 upm00 usbs0 ucsz01 /udord0 ucsz00 / ucpha0 ucpol0 183 / 193 (0xc1) ucsr0b rxcie0 txcie0 udrie0 rxen0 txen0 ucsz02 rxb80 txb80 182 (0xc0) ucsr0a rxc0 txc0 udre0 fe0 dor0 upe0 u2x0 mpcm0 181 (0xbf) reserved ? ? ? ? ? ? ? ? (0xbe) reserved ? ? ? ? ? ? ? ? (0xbd) twamr twam6 twam5 twam4 twam3 twam2 twam1 twam0 ? 222 (0xbc) twcr twint twea twsta twsto twwc twen ?twie 219 (0xbb) twdr 2-wire serial interface data register 221 (0xba) twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce 222 (0xb9) twsr tws7 tws6 tws5 tws4 tws3 ? twps1 twps0 221 (0xb8) twbr 2-wire serial interface bit rate register 219 (0xb7) reserved ? ? ? ? ? ? ? (0xb6) assr ? exclk as2 tcn2ub ocr2aub ocr2bub tcr2aub tcr2bub 155 5.30 register summary (continued) address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page notes: 1. for compatibility with future devices, reserved bits sh ould be written to zero if accessed. reserved i/o memory addresses should never be written. 2. i/o registers within the address range 0x00 - 0x1f are direct ly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be c hecked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avr ? s, the cbi and sbi instructions will only operate on t he specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions wo rk with registers 0x00 to 0x1f only. 4. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega328p is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used.
ata6614q [datasheet] 9240h?auto?10/14 296 (0xb5) reserved ? ? ? ? ? ? ? ? (0xb4) ocr2b timer/counter2 output compare register b 154 (0xb3) ocr2a timer/counter2 output compare register a 154 (0xb2) tcnt2 timer/counter2 (8-bit) 154 (0xb1) tccr2b foc2a foc2b ? ? wgm22 cs22 cs21 cs20 153 (0xb0) tccr2a com2a1 com2a0 com2b1 com2b0 ? ?wgm21wgm20 150 (0xaf) reserved ? ? ? ? ? ? ? ? (0xae) reserved ? ? ? ? ? ? ? ? (0xad) reserved ? ? ? ? ? ? ? ? (0xac) reserved ? ? ? ? ? ? ? ? (0xab) reserved ? ? ? ? ? ? ? ? (0xaa) reserved ? ? ? ? ? ? ? ? (0xa9) reserved ? ? ? ? ? ? ? ? (0xa8) reserved ? ? ? ? ? ? ? ? (0xa7) reserved ? ? ? ? ? ? ? ? (0xa6) reserved ? ? ? ? ? ? ? ? (0xa5) reserved ? ? ? ? ? ? ? ? (0xa4) reserved ? ? ? ? ? ? ? ? (0xa3) reserved ? ? ? ? ? ? ? ? (0xa2) reserved ? ? ? ? ? ? ? ? (0xa1) reserved ? ? ? ? ? ? ? ? (0xa0) reserved ? ? ? ? ? ? ? ? (0x9f) reserved ? ? ? ? ? ? ? ? (0x9e) reserved ? ? ? ? ? ? ? ? (0x9d) reserved ? ? ? ? ? ? ? ? (0x9c) reserved ? ? ? ? ? ? ? ? (0x9b) reserved ? ? ? ? ? ? ? ? (0x9a) reserved ? ? ? ? ? ? ? ? (0x99) reserved ? ? ? ? ? ? ? ? (0x98) reserved ? ? ? ? ? ? ? ? (0x97) reserved ? ? ? ? ? ? ? ? (0x96) reserved ? ? ? ? ? ? ? ? (0x95) reserved ? ? ? ? ? ? ? ? (0x94) reserved ? ? ? ? ? ? ? ? (0x93) reserved ? ? ? ? ? ? ? ? (0x92) reserved ? ? ? ? ? ? ? ? (0x91) reserved ? ? ? ? ? ? ? ? (0x90) reserved ? ? ? ? ? ? ? ? 5.30 register summary (continued) address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page notes: 1. for compatibility with future devices, reserved bits sh ould be written to zero if accessed. reserved i/o memory addresses should never be written. 2. i/o registers within the address range 0x00 - 0x1f are direct ly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be c hecked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avr ? s, the cbi and sbi instructions will only operate on t he specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions wo rk with registers 0x00 to 0x1f only. 4. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega328p is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used.
297 ata6614q [datasheet] 9240h?auto?10/14 (0x8f) reserved ? ? ? ? ? ? ? ? (0x8e) reserved ? ? ? ? ? ? ? ? (0x8d) reserved ? ? ? ? ? ? ? ? (0x8c) reserved ? ? ? ? ? ? ? ? (0x8b) ocr1bh timer/counter1 - output compare register b high byte 134 (0x8a) ocr1bl timer/counter1 - output compare register b low byte 134 (0x89) ocr1ah timer/counter1 - output compare register a high byte 134 (0x88) ocr1al timer/counter1 - output compare register a low byte 134 (0x87) icr1h timer/counter1 - input capture register high byte 135 (0x86) icr1l timer/counter1 - input capture register low byte 135 (0x85) tcnt1h timer/counter1 - counter register high byte 134 (0x84) tcnt1l timer/counter1 - counter register low byte 134 (0x83) reserved ? ? ? ? ? ? ? ? (0x82) tccr1c foc1a foc1b ? ? ? ? ? ? 134 (0x81) tccr1b icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 133 (0x80) tccr1a com1a1 com1a0 com1b1 com1b0 ? ?wgm11wgm10 131 (0x7f) didr1 ? ? ? ? ? ?ain1dain0d 225 (0x7e) didr0 ? ? adc5d adc4d adc3d adc2d adc1d adc0d 241 (0x7d) reserved ? ? ? ? ? ? ? ? (0x7c) admux refs1 refs0 adlar ? mux3 mux2 mux1 mux0 237 (0x7b) adcsrb ?acme ? ? ? adts2 adts1 adts0 241 (0x7a) adcsra aden adsc adate adif adie adps2 adps1 adps0 239 (0x79) adch adc data register high byte 240 (0x78) adcl adc data register low byte 240 (0x77) reserved ? ? ? ? ? ? ? ? (0x76) reserved ? ? ? ? ? ? ? ? (0x75) reserved ? ? ? ? ? ? ? ? (0x74) reserved ? ? ? ? ? ? ? ? (0x73) reserved ? ? ? ? ? ? ? ? (0x72) reserved ? ? ? ? ? ? ? ? (0x71) reserved ? ? ? ? ? ? ? ? (0x70) timsk2 ? ? ? ? ? ocie2b ocie2a toie2 154 (0x6f) timsk1 ? ?icie1 ? ? ocie1b ocie1a toie1 135 (0x6e) timsk0 ? ? ? ? ? ocie0b ocie0a toie0 111 (0x6d) pcmsk2 pcint23 pcint22 pcint21 pcint20 pcint19 pcint18 pcint17 pcint16 81 (0x6c) pcmsk1 ? pcint14 pcint13 pcint12 pcint11 pcint10 pcint9 pcint8 81 (0x6b) pcmsk0 pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 81 (0x6a) reserved ? ? ? ? ? ? ? ? 5.30 register summary (continued) address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page notes: 1. for compatibility with future devices, reserved bits sh ould be written to zero if accessed. reserved i/o memory addresses should never be written. 2. i/o registers within the address range 0x00 - 0x1f are direct ly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be c hecked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avr ? s, the cbi and sbi instructions will only operate on t he specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions wo rk with registers 0x00 to 0x1f only. 4. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega328p is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used.
ata6614q [datasheet] 9240h?auto?10/14 298 (0x69) eicra ? ? ? ? isc11 isc10 isc01 isc00 78 (0x68) pcicr ? ? ? ? ? pcie2 pcie1 pcie0 (0x67) reserved ? ? ? ? ? ? ? ? (0x66) osccal oscillator calibration register 57 (0x65) reserved ? ? ? ? ? ? ? ? (0x64) prr prtwi prtim2 prtim0 ? prtim1 prspi prusart0 pradc 60 (0x63) reserved ? ? ? ? ? ? ? ? (0x62) reserved ? ? ? ? ? ? ? ? (0x61) clkpr clkpce ? ? ? clkps3 clkps2 clkps1 clkps0 57 (0x60) wdtcsr wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 71 0x3f (0x5f) sreg i t h s v n z c 34 0x3e (0x5e) sph ? ? ? ? ? (sp10) sp9 sp8 37 0x3d (0x5d) spl sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 37 0x3c (0x5c) reserved ? ? ? ? ? ? ? ? 0x3b (0x5b) reserved ? ? ? ? ? ? ? ? 0x3a (0x5a) reserved ? ? ? ? ? ? ? ? 0x39 (0x59) reserved ? ? ? ? ? ? ? ? 0x38 (0x58) reserved ? ? ? ? ? ? ? ? 0x37 (0x57) spmcsr spmie (rwwsb) ? (rwwsre) blbset pgwrt pgers selfprgen 261 0x36 (0x56) reserved ? ? ? ? ? ? ? ? 0x35 (0x55) mcucr ? bods bodse pud ? ? ivsel ivce 62 / 76 / 96 0x34 (0x54) mcusr ? ? ? ? wdrf borf extrf porf 71 0x33 (0x53) smcr ? ? ? ? sm2 sm1 sm0 se 59 0x32 (0x52) reserved ? ? ? ? ? ? ? ? 0x31 (0x51) reserved ? ? ? ? ? ? ? ? 0x30 (0x50) acsr acd acbg aco aci acie acic acis1 acis0 224 0x2f (0x4f) reserved ? ? ? ? ? ? ? ? 0x2e (0x4e) spdr spi data register 164 0x2d (0x4d) spsr spif wcol ? ? ? ? ? spi2x 164 0x2c (0x4c) spcr spie spe dord mstr cpol cpha spr1 spr0 163 0x2b (0x4b) gpior2 general purpose i/o register 2 47 0x2a (0x4a) gpior1 general purpose i/o register 1 47 0x29 (0x49) reserved ? ? ? ? ? ? ? ? 0x28 (0x48) ocr0b timer/counter0 output compare register b 0x27 (0x47) ocr0a timer/counter0 output compare register a 0x26 (0x46) tcnt0 timer/counter0 (8-bit) 0x25 (0x45) tccr0b foc0a foc0b ? ? wgm02 cs02 cs01 cs00 0x24 (0x44) tccr0a com0a1 com0a0 com0b1 com0b0 ? ?wgm01wgm00 5.30 register summary (continued) address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page notes: 1. for compatibility with future devices, reserved bits sh ould be written to zero if accessed. reserved i/o memory addresses should never be written. 2. i/o registers within the address range 0x00 - 0x1f are direct ly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be c hecked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avr ? s, the cbi and sbi instructions will only operate on t he specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions wo rk with registers 0x00 to 0x1f only. 4. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega328p is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used.
299 ata6614q [datasheet] 9240h?auto?10/14 0x23 (0x43) gtccr tsm ? ? ? ? ? psrasy psrsync 138 / 156 0x22 (0x42) eearh (eeprom addr ess register high byte) 43 0x21 (0x41) eearl eeprom address register low byte 43 0x20 (0x40) eedr eeprom data register 44 0x1f (0x3f) eecr ? ? eepm1 eepm0 eerie eempe eepe eere 44 0x1e (0x3e) gpior0 general purpose i/o register 0 47 0x1d (0x3d) eimsk ? ? ? ? ? ? int1 int0 79 0x1c (0x3c) eifr ? ? ? ? ? ? intf1 intf0 79 0x1b (0x3b) pcifr ? ? ? ? ? pcif2 pcif1 pcif0 0x1a (0x3a) reserved ? ? ? ? ? ? ? ? 0x19 (0x39) reserved ? ? ? ? ? ? ? ? 0x18 (0x38) reserved ? ? ? ? ? ? ? ? 0x17 (0x37) tifr2 ? ? ? ? ? ocf2b ocf2a tov2 155 0x16 (0x36) tifr1 ? ?icf1 ? ? ocf1b ocf1a tov1 136 0x15 (0x35) tifr0 ? ? ? ? ? ocf0b ocf0a tov0 0x14 (0x34) reserved ? ? ? ? ? ? ? ? 0x13 (0x33) reserved ? ? ? ? ? ? ? ? 0x12 (0x32) reserved ? ? ? ? ? ? ? ? 0x11 (0x31) reserved ? ? ? ? ? ? ? ? 0x10 (0x30) reserved ? ? ? ? ? ? ? ? 0x0f (0x2f) reserved ? ? ? ? ? ? ? ? 0x0e (0x2e) reserved ? ? ? ? ? ? ? ? 0x0d (0x2d) reserved ? ? ? ? ? ? ? ? 0x0c (0x2c) reserved ? ? ? ? ? ? ? ? 0x0b (0x2b) portd portd7 portd6 portd 5 portd4 portd3 portd2 portd1 portd0 97 0x0a (0x2a) ddrd ddd7 ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 97 0x09 (0x29) pind pind7 pind6 pind5 pind4 pind3 pind2 pind1 pind0 97 0x08 (0x28) portc ? portc6 portc5 portc4 portc3 portc2 portc1 portc0 97 0x07 (0x27) ddrc ? ddc6 ddc5 ddc4 ddc3 ddc2 ddc1 ddc0 97 0x06 (0x26) pinc ? pinc6 pinc5 pinc4 pinc3 pinc2 pinc1 pinc0 97 0x05 (0x25) portb portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 96 0x04 (0x24) ddrb ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 96 0x03 (0x23) pinb pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 97 0x02 (0x22) reserved ? ? ? ? ? ? ? ? 0x01 (0x21) reserved ? ? ? ? ? ? ? ? 0x0 (0x20) reserved ? ? ? ? ? ? ? ? 5.30 register summary (continued) address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page notes: 1. for compatibility with future devices, reserved bits sh ould be written to zero if accessed. reserved i/o memory addresses should never be written. 2. i/o registers within the address range 0x00 - 0x1f are direct ly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be c hecked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avr ? s, the cbi and sbi instructions will only operate on t he specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions wo rk with registers 0x00 to 0x1f only. 4. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega328p is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used.
ata6614q [datasheet] 9240h?auto?10/14 300 5.31 instruction set summary mnemonics operands description operation flags #clocks arithmetic and logic instructions add rd, rr add two registers rd rd + rr z,c,n,v,h 1 adc rd, rr add with carry two registers rd rd + rr + c z,c,n,v,h 1 adiw rdl,k add immediate to word rdh:rdl rdh:rdl + k z,c,n,v,s 2 sub rd, rr subtract two registers rd rd - rr z,c,n,v,h 1 subi rd, k subtract constant from register rd rd - k z,c,n,v,h 1 sbc rd, rr subtract with carry two registers rd rd - rr - c z,c,n,v,h 1 sbci rd, k subtract with carry constant from reg. rd rd - k - c z,c,n,v,h 1 sbiw rdl,k subtract immediate from word rdh:rdl rdh:rdl - k z,c,n,v,s 2 and rd, rr logical and registers rd rd ? rr z,n,v 1 andi rd, k logical and register and constant rd rd ? k z,n,v 1 or rd, rr logical or registers rd rd v rr z,n,v 1 ori rd, k logical or register and constant rd rd v k z,n,v 1 eor rd, rr exclusive or registers rd rd rr z,n,v 1 com rd one?s complement rd 0xff ? rd z,c,n,v 1 neg rd two?s complement rd 0x00 ? rd z,c,n,v,h 1 sbr rd,k set bit(s) in register rd rd v k z,n,v 1 cbr rd,k clear bit(s) in register rd rd ? (0xff - k) z,n,v 1 inc rd increment rd rd + 1 z,n,v 1 dec rd decrement rd rd ? 1 z,n,v 1 tst rd test for zero or minus rd rd ? rd z,n,v 1 clr rd clear register rd rd rd z,n,v 1 ser rd set register rd 0xff none 1 mul rd, rr multiply unsigned r1:r0 rd x rr z,c 2 muls rd, rr multiply signed r1:r0 rd x rr z,c 2 mulsu rd, rr multiply signed with unsigned r1:r0 rd x rr z,c 2 fmul rd, rr fractional multiply unsigned r1:r0 (rd x rr) << 1 z,c 2 fmuls rd, rr fractional multiply signed r1:r0 (rd x rr) << 1 z,c 2 fmulsu rd, rr fractional multiply signed with unsigned r1:r0 (rd x rr) << 1 z,c 2 branch instructions rjmp k relative jump pc pc + k + 1 none 2 ijmp indirect jump to (z) pc z none 2 jmp k direct jump pc k none 3 rcall k relative subroutine call pc pc + k + 1 none 3 icall indirect call to (z) pc z none 3 call k direct subroutine call pc k none 4 ret subroutine return pc stack none 4 reti interrupt return pc stack i 4 cpse rd,rr compare, skip if equal if (rd = rr) pc pc + 2 or 3 none 1/2/3 cp rd,rr compare rd ? rr z, n,v,c,h 1 cpc rd,rr compare with carry rd ? rr ? c z, n,v,c,h 1 cpi rd,k compare register with immediate rd ? k z, n,v,c,h 1 sbrc rr, b skip if bit in register cleared if (rr(b)=0) pc pc + 2 or 3 none 1/2/3 sbrs rr, b skip if bit in register is set if (rr(b)=1) pc pc + 2 or 3 none 1/2/3 sbic p, b skip if bit in i/o register cleared if (p(b)=0) pc pc + 2 or 3 none 1/2/3 sbis p, b skip if bit in i/o register is set if (p(b)=1) pc pc + 2 or 3 none 1/2/3
301 ata6614q [datasheet] 9240h?auto?10/14 brbs s, k branch if status flag set if (sreg(s) = 1) then pc pc+k + 1 none 1/2 brbc s, k branch if status flag cleared if (sreg(s) = 0) then pc pc+k + 1 none 1/2 breq k branch if equal if (z = 1) then pc pc + k + 1 none 1/2 brne k branch if not equal if (z = 0) then pc pc + k + 1 none 1/2 brcs k branch if carry set if (c = 1) then pc pc + k + 1 none 1/2 brcc k branch if carry cleared if (c = 0) then pc pc + k + 1 none 1/2 brsh k branch if same or higher if (c = 0) then pc pc + k + 1 none 1/2 brlo k branch if lower if (c = 1) then pc pc + k + 1 none 1/2 brmi k branch if minus if (n = 1) then pc pc + k + 1 none 1/2 brpl k branch if plus if (n = 0) then pc pc + k + 1 none 1/2 brge k branch if greater or equal, signed if (n v= 0) then pc pc + k + 1 none 1/2 brlt k branch if less than zero, signed if (n v= 1) then pc pc + k + 1 none 1/2 brhs k branch if half carry flag set if (h = 1) then pc pc + k + 1 none 1/2 brhc k branch if half carry flag cleared if (h = 0) then pc pc + k + 1 none 1/2 brts k branch if t flag set if (t = 1) then pc pc + k + 1 none 1/2 brtc k branch if t flag cleared if (t = 0) then pc pc + k + 1 none 1/2 brvs k branch if overflow flag is set if (v = 1) then pc pc + k + 1 none 1/2 brvc k branch if overflow flag is cleared if (v = 0) then pc pc + k + 1 none 1/2 brie k branch if interrupt enabled if ( i = 1) then pc pc + k + 1 none 1/2 brid k branch if interrupt disabled if ( i = 0) then pc pc + k + 1 none 1/2 bit and bit-test instructions sbi p, b set bit in i/o register i/o(p,b) 1 none 2 cbi p, b clear bit in i/o register i/o(p,b) 0 none 2 lsl rd logical shift left rd(n+1) rd(n), rd(0) 0 z,c,n,v 1 lsr rd logical shift right rd(n) rd(n+1), rd(7) 0 z,c,n,v 1 rol rd rotate left through carry rd(0) c,rd(n+1) rd(n),c rd(7) z,c,n,v 1 ror rd rotate right through carry rd(7) c,rd(n) rd(n+1),c rd(0) z,c,n,v 1 asr rd arithmetic shift right rd(n) rd(n+1), n=0..6 z,c,n,v 1 swap rd swap nibbles rd(3..0) rd(7..4),rd(7..4) rd(3..0) none 1 bset s flag set sreg(s) 1 sreg(s) 1 bclr s flag clear sreg(s) 0 sreg(s) 1 bst rr, b bit store from register to t t rr(b) t 1 bld rd, b bit load from t to register rd(b) t none 1 sec set carry c 1 c 1 clc clear carry c 0 c 1 sen set negative flag n 1 n 1 cln clear negative flag n 0 n 1 sez set zero flag z 1 z 1 clz clear zero flag z 0 z 1 sei global interrupt enable i 1 i 1 cli global interrupt disable i 0 i 1 ses set signed test flag s 1 s 1 cls clear signed test flag s 0 s 1 sev set twos complement overflow. v 1 v 1 clv clear twos complement overflow v 0 v 1 set set t in sreg t 1 t 1 5.31 instruction set summary (continued) mnemonics operands description operation flags #clocks
ata6614q [datasheet] 9240h?auto?10/14 302 clt clear t in sreg t 0 t 1 seh set half carry flag in sreg h 1 h 1 clh clear half carry flag in sreg h 0 h 1 data transfer instructions mov rd, rr move between registers rd rr none 1 movw rd, rr copy register word rd+1:rd rr+1:rr none 1 ldi rd, k load immediate rd k none 1 ld rd, x load indirect rd (x) none 2 ld rd, x+ load indirect and post-inc. rd (x), x x + 1 none 2 ld rd, - x load indirect and pre-dec. x x - 1, rd (x) none 2 ld rd, y load indirect rd (y) none 2 ld rd, y+ load indirect and post-inc. rd (y), y y + 1 none 2 ld rd, - y load indirect and pre-dec. y y - 1, rd (y) none 2 ldd rd,y+q load indirect with displacement rd (y + q) none 2 ld rd, z load indirect rd (z) none 2 ld rd, z+ load indirect and post-inc. rd (z), z z+1 none 2 ld rd, -z load indirect and pre-dec. z z - 1, rd (z) none 2 ldd rd, z+q load indirect with displacement rd (z + q) none 2 lds rd, k load direct from sram rd (k) none 2 st x, rr store indirect (x) rr none 2 st x+, rr store indirect and post-inc. (x) rr, x x + 1 none 2 st - x, rr store indirect and pre-dec. x x - 1, (x) rr none 2 st y, r r store indirect (y) rr none 2 st y+, rr store indirect and post-inc. (y) rr, y y + 1 none 2 st - y, rr store indirect and pre-dec. y y - 1, (y) rr none 2 std y+q,rr store indirect with displacement (y + q) rr none 2 st z, rr store indirect (z) rr none 2 st z+, rr store indirect and post-inc. (z) rr, z z + 1 none 2 st -z, rr store indirect and pre-dec. z z - 1, (z) rr none 2 std z+q,rr store indirect with displacement (z + q) rr none 2 sts k, rr store direct to sram (k) rr none 2 lpm load program memory r0 (z) none 3 lpm rd, z load program memory rd (z) none 3 lpm rd, z+ load program memory and post-inc rd (z), z z+1 none 3 spm store program memory (z) r1:r0 none - in rd, p in port rd p none 1 out p, r r out port p rr none 1 push rr push register on stack stack rr none 2 pop rd pop register from stack rd stack none 2 mcu control instructions nop no operation none 1 sleep sleep (see specific descr. for sleep function) none 1 wdr watchdog reset (see specific descr . for wdr/timer) none 1 break break for on-chip debug only none n/a 5.31 instruction set summary (continued) mnemonics operands description operation flags #clocks
303 ata6614q [datasheet] 9240h?auto?10/14 6. application figure 6-1. typical lin slave application note: all open pins of the sip can be used for application-specific purposes. avr ? : internal clock, no adc application, txd, rxd, nres, en and ntrig connected for lin slave. the connection between the lin-sbc and the avr requires the software being programmed correspondingly. sbc: lin slave operation with watchd og, 5v regulator and kl15 wake up rf emissions: best results for rf emissions will be achi eved by connecting the blocking capacitors of the microcontroller supply (c1 and c2) between the micr ocontroller pins and the gnd/pvcc line. see also figure 6-1 . + ata6614q gnd kl_15 vbat lin isp pb3 pvcc pb5 pc6 pb4 22f 100nf 10f 100nf 100nf 100nf 220pf inh pvcc gnd wd_osc tm mode kl_15 rxd inh tdx nres pc6 pd0 pd1 pd2 48 47 46 45 40 39 38 37 44 43 42 41 13 14 15 16 21 22 23 24 17 18 19 20 pb7 pb6 mcuvcc gnd2 mcuvcc gnd1 pd4 lin pd3 wake ntrig en vs vcc pvcc 10 9 12 11 6 5 8 7 2 1 4 3 27 28 25 26 31 32 29 30 35 36 33 34 pb5 pb0 pd7 pd6 pd5 pb4 pb3 pb2 pb1 mcuavcc adc6 gnd4 aref adc7 pc0 pc1 pc2 pc3 pc4 pc5 1 + 10k 47k 51k c2 100nf c1 100nf atmel 10k * mode * * the mode pin can be connected directly to gnd, if it is not needed to disable the watchdog pb3 pb4 pb5 pc6
ata6614q [datasheet] 9240h?auto?10/14 304 figure 6-2. typical lin master application note: all open pins of the sip can be used for application-specific purposes. avr ? : txd, rxd, nres and en connected for lin ma ster. the connection between the lin-sbc and the avr requires the software being pr ogrammed correspondingly. analog di gital converter not active; system clock from external crystal. lin-sbc: master application with 5v regulator and watchdog, 1k mast er resistance connected via diode to vbat, local wake up via pin wake. rf emissions: best results for rf emissions will be achi eved by connecting the blocking capacitors of the microcontroller supply (c1 and c2) between the micr ocontroller pins and the gnd/pvcc line. see also figure 6-2 . + ata6614q xtal gnd vbat lin isp wake pb3 pvcc pb5 pc6 pb4 22f 100nf 10f 100nf 100nf 560pf 22pf 22pf pvcc gnd wd_osc tm mode kl_15 rxd inh tdx nres pc6 pd0 pd1 pd2 48 47 46 45 40 39 38 37 44 43 42 41 13 14 15 16 21 22 23 24 17 18 19 20 pb7 pb6 mcuvcc gnd2 mcuvcc gnd1 pd4 lin pd3 wake ntrig en vs vcc pvcc 10 9 12 11 6 5 8 7 2 1 4 3 27 28 25 26 31 32 29 30 35 36 33 34 pb5 pb0 pd7 pd6 pd5 pb4 pb3 pb2 pb1 mcuavcc adc6 gnd4 aref adc7 pc0 pc1 pc2 pc3 pc4 pc5 2.7 k 10k 1k 1 + c2 100nf c1 100nf 10k atmel 51k mode * 10k * * the mode pin can be connected directly to gnd, if it is not needed to disable the watchdog pb3 pb4 pb5 pc6
305 ata6614q [datasheet] 9240h?auto?10/14 figure 6-3. typical lin master application lin master pull-up switched off during sleep mode note: all open pins of the sip can be used for application-specific purposes. avr ? : txd, rxd, nres and en connected for lin ma ster. the connection between the lin-sbc and the avr requires the software being pr ogrammed correspondingly. analog di gital converter not active; system clock from external crystal. lin-sbc: master application with 5v regulator and watchdog, 1k mast er resistance connected via diode and inh output to vbat, lo cal wake up via pin wake. rf emissions: best results for rf emissions will be achi eved by connecting the blocking capacitors of the microcontroller supply (c1 and c2) between the micr ocontroller pins and the gnd/pvcc line. see also figure 6-3 . + ata6614q xtal gnd vbat lin isp wake pb3 pvcc pb5 pc6 pb4 22f 100nf 10f 100nf 100nf 560pf 22pf 22pf pvcc gnd wd_osc tm mode kl_15 rxd inh tdx nres pc6 pd0 pd1 pd2 48 47 46 45 40 39 38 37 44 43 42 41 13 14 15 16 21 22 23 24 17 18 19 20 pb7 pb6 mcuvcc gnd2 mcuvcc gnd1 pd4 lin pd3 wake ntrig en vs vcc pvcc 10 9 12 11 6 5 8 7 2 1 4 3 27 28 25 26 31 32 29 30 35 36 33 34 pb5 pb0 pd7 pd6 pd5 pb4 pb3 pb2 pb1 mcuavcc adc6 gnd4 aref adc7 pc0 pc1 pc2 pc3 pc4 pc5 2.7k 10k 1k 1 + c2 100nf c1 100nf 10k 10k atmel 51 k 10k * mode * * the mode pin can be connected directly to gnd, if it is not needed to disable the watchdog pb3 pb4 pb5 pc6
ata6614q [datasheet] 9240h?auto?10/14 306 figure 6-4. lin slave application with minimum external components note: all open pins of the sip can be used for application-specific purposes. avr ? : internal clock, no adc application, txd, rxd, nres and en connected for lin slave. the connection between the lin-sbc and the avr requires the software being programmed correspondingly. sbc: lin slave operation with 5v regu lator, no watchdog, no local wake-up. rf emissions: best results for rf emissions will be achi eved by connecting the blocking capacitors of the microcontroller supply (c1 and c2) between the micr ocontroller pins and the gnd/pvcc line. see also figure 6-4 . + ata6614q gnd vbat lin isp pb3 pvcc pb5 pc6 pb4 22f 100nf 10f 100nf 100nf 220pf pvcc gnd wd_osc tm mode kl_15 rxd inh tdx nres pc6 pd0 pd1 pd2 48 47 46 45 40 39 38 37 44 43 42 41 13 14 15 16 21 22 23 24 17 18 19 20 pb7 pb6 mcuvcc gnd2 mcuvcc gnd1 pd4 lin pd3 wake ntrig en vs vcc pvcc 10 9 12 11 6 5 8 7 2 1 4 3 27 28 25 26 31 32 29 30 35 36 33 34 pb5 pb0 pd7 pd6 pd5 pb4 pb3 pb2 pb1 mcuavcc adc6 gnd4 aref adc7 pc0 pc1 pc2 pc3 pc4 pc5 1 + 10k c1 100nf c2 100nf atmel pb3 pb4 pb5 pc6
307 ata6614q [datasheet] 9240h?auto?10/14 8. package information 7. ordering information extended type number program memory package moq ata6614q-plqw-1 32kb flash qfn48, 7 7 4,000 pieces package drawing contact: packagedrawings@atmel.com gpc drawing no. rev. title 6.543-5188.03-4 1 05/20/14 package: qfn_7x7_48l exposed pad 5.6x5.6 common dimensions (unit of measure = mm) min nom note max symbol dimensions in mm specifications according to din technical drawings 0.035 0.05 0 a1 77.1 6.9 e 0.25 0.3 0.2 b 0.5 e 0.4 0.45 0.35 l 5.6 5.7 5.5 e2 5.6 5.7 5.5 d2 77.1 6.9 d 0.21 0.26 0.16 a3 0.85 0.9 0.8 a b l a (10:1) a d 1 12 48 pin 1 id e top view a a3 a1 e2 side view bottom view e d2 48 37 13 12 1 24 25 36
ata6614q [datasheet] 9240h?auto?10/14 308 9. revision history please note that the following page numbers re ferred to in this section re fer to the specific revision mentioned, not to this document. revision no. history 9240h-auto-10/14 ? section 2 ?pin configuration? on pages 3 to 4 updated ? section 3 ?absolute maximum ratings? on pages 5 to 6 added ? section 4.4.2 ?silent mode? on page 12 updated ? section 6 ?application? on pages 303 to 306 updated ? section 7 ?ordering information? on page 307 updated ? section 8 ?package information? on page 307 updated 9240g-auto-11/12 ? section 8 ?ordering information? on page 364 updated ? set datasheet from preliminary to standard 9240f-auto-10/12 ? atmega88p and atmega168p references removed ? section 4 ?absolute maximum ratings? on page 24 updated ? section 6.1 ?features? on page 31 updated 9240e-auto-07/12 ? section 4 ?absolute maximum ratings? on page 24 updated 9240d-auto-06/12 ? section 6 ?microcontroller block? on pages 31 to 359 updated 9240c-auto-05/12 ? section 6.28.1 ?absolute maximum ratings? on page 340 changed ? section 6.28.2 ?dc characteristics? on page 340 changed 9240b-auto-02/12 ? ata6614p renamed to ata6614q on all pages ? general features on page 1 changed ? table 2-1 ?pin description? on page 3 changed ? section 3.4.6 ?unpowered mode? on pages 17 to 18 changed ? section 3.6 ?voltage regulator? on page 21 changed ? section 7 ?application? on page 456 added
309 ata6614q [datasheet] 9240h?auto?10/14 10. table of contents general features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1. description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 2. pin configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 3. absolute maximum ratings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 4. lin system-basis-chip block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 4.1 features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 4.2 description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 4.3 functional description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 4.4 modes of operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 4.5 wake-up scenarios from silent or sleep mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 4.6 voltage regulator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 4.7 watchdog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 4.8 electrical characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5. microcontroller block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 0 5.1 features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 5.2 overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 5.3 resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 5.4 data retention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 5.5 about code examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 5.6 avr cpu core . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 5.7 avr memories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 5.8 system clock and clock options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 5.9 power management and sleep modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 5.10 system control and reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 5.11 interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 5.12 external interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 5.13 i/o-ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 5.14 8-bit timer/counter0 with pwm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 5.15 16-bit timer/counter1 with pwm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 5.16 timer/counter0 and timer/counter1 prescalers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 5.17 8-bit timer/counter2 with pwm and asynchronous operation . . . . . . . . . . . . . . . . . . . . . 139 5.18 spi ? serial peripheral interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 5.19 usart0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 5.20 usart in spi mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 5.21 2-wire serial interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 5.22 analog comparator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 5.23 analog-to-digital converter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 5.24 debugwire on-chip debug system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 5.25 self-programming the flash, atmega328p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 5.26 boot loader support ? read-while-write self-programming . . . . . . . . . . . . . . . . . . . . . . . 250 5.27 memory programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 5.28 electrical characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 5.29 typical characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 5.30 register summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294 5.31 instruction set summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 6. application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 7. ordering information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
ata6614q [datasheet] 9240h?auto?10/14 310 8. package information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 9. revision history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 08 10. table of contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 09
x x xx x x atmel corporation 1600 technology drive, san jose, ca 95110 usa t: (+1)(408) 441.0311 f: (+1)(408) 436.4200 | www.atmel.com ? 2014 atmel corporation. / rev.: 9240h?auto?10/14 atmel ? , atmel logo and combinations thereof, enabling unlimited possibilities ? , avr ? , and others are registered trademarks or trademarks of atmel corporation in u.s. and other countries. other terms and product names may be trademarks of others. disclaimer: the information in this document is provided in c onnection with atmel products. no license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of atmel products. except as set forth in the atmel terms and condit ions of sales located on the atmel website, atmel assumes no liability wh atsoever and disclaims any express, implied or statutory warranty relating to its p roducts including, but not limited to, the implied warranty of merchantability, fitness for a particular purpose, or non-infringement. in no event shall atmel be liable for any direct, indirect, consequential, pu nitive, special or incidental damages (including, without limi tation, damages for loss and profits, business interruption, or loss of information ) arising out of the use or inability to use this document, even if atmel has been advised of the possibility of such damages. atmel makes no r epresentations or warranties with respect to the accuracy or c ompleteness of the contents of this document and reserves the right to make changes to specificatio ns and products descriptions at any time without notice. atmel d oes not make any commitment to update the information contained herein. unless specifically provided otherwise, atme l products are not suitable for, and shall not be used in, automo tive applications. atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life. safety-critical, military, and automotive applications disclaim er: atmel products are not designed for and will not be used in connection with any applications where the failure of such products would reasonably be expected to re sult in significant personal inju ry or death (?safety-critical a pplications?) without an atmel officer's specific written consent. safety-critical applications incl ude, without limitation, life support devices and systems, equipment or systems for t he operation of nuclear facilities and weapons systems. atmel products are not designed nor intended for use in military or aerospace applications or environments unless specifically designated by atmel as military-grade. atmel products are not designed nor intended for use in automot ive applications unless spec ifically designated by atmel as automotive-grade.


▲Up To Search▲   

 
Price & Availability of ATA6614Q-14

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X